Call assembly procedure from another assembly file

2019-07-20 13:20发布

问题:

Just a simple question:

Let's say I had the following two assembly programs:

1:

add10:
   add eax, 10
   ret
;call add5 from other file

2:

add5:
   add eax, 5
   ret
;call add10 from other file

Could I call add10 (declared in the first file) from the second file, or vice-versa? If so, how can it be done? (even if it isn't feasible)

NOTE: This will be running on bare metal, not on any fancy NT calls!

Thanks.

Edit: I'm using NASM on Windows.

回答1:

If both files are linked into the same executable, yes. Lookup EXTERN or EXTRN.



回答2:

Two files:

1:

BITS 32

GLOBAL add5

section .code
add5:
    add eax, 5
    ret

2:

BITS 32

EXTERN add5
EXTERN printf
EXTERN ExitProcess

section .data
    fmt db `eax=%u\n`

section .code
add10:
    add eax, 5
    call add5
    ret

_main:
    mov eax, 87
    call add10

    push eax
    push fmt
    call printf
    add esp, 8

    push 0
    call ExitProcess

Assemble & link them together. I used as linker GoLink, other linkers are similar:

nasm.exe -fwin32 -o add5.obj add5.asm
nasm.exe -fwin32 -o add10.obj add10.asm
GoLink.exe /ENTRY:_main /console /fo add10.exe add5.obj add10.obj kernel32.dll msvcrt.dll

I named the sources "add5.asm" and "add10.asm". The assembler produces "add5.obj" and "add10.obj". The linker uses "add5.obj" and "add10.obj" and some system libraries (for 'printf' and 'ExitProcess'). The result is the executable "add10.exe". Look at the command lines to get the order of those names. The names are arbitrary.

HTH