1

I would like to split my nasm code into several files, so that I can work on different pieces of code separately. However, the only way I found is using nasm %include macro. For example. main.asm file looks somewhat like this,

; ---- main.asm ----
%include "./header.asm"

section .text
    global _start
_start:

    call dummy_func

    mov rax, 0x3c
    mov rdx, 0x0
    syscall

while header.asm only contains

section .text
dummy_func:
        ret

I have heard about a way to do this during linking. I got very interested in that, but couldn't find anything appropriate. Is it really possible? If so, can it be done with ld? What other means are there to include a static library? (probably some more macros. However I'm not sure "macros" is the right word here)

MinuxLint
  • 111
  • 9

1 Answers1

2

No need for static libraries - you can declare the function as external. In your case, main.asm would look like:

; ---- main.asm ----
section .text
    global _start
    extern dummy_func
_start:

    call dummy_func

    mov rax, 0x3c
    mov rdx, 0x0
    syscall

Then compile your source files to object files:

nasm main.asm -o main.o
nasm header.asm -o header.o

Then you can finally use ld to link the 2 object files into a single executable:

ld -o [desired executable name] main.o header.o

The extern keyword basically means the function dummy_func is located in a different object file, and that the object file containing dummy_func MUST be linked into the executable at the end. This is a much better way of doing things than using %include.

J. S.
  • 61
  • 4
  • Thank you. But don't I have to declare dummy_func as a global label? It only works this way – MinuxLint Apr 26 '20 at 18:36
  • In main.asm you declare it as extern, however in header.asm you declare it as global. In general, anywhere you want to use a function put it as `extern`, and in the source file where it's actually defined put it as `global`. – J. S. Apr 26 '20 at 18:51