Linking object files
Splitting into objects
Each source assembles to one object. Symbols you export are global; symbols you import are extern. The linker joins them by name:
; main.asm
extern print_string
section .data
msg db "hello from another object", 10
len equ $ - msg
section .text
global _start
_start:
mov rdi, msg
mov rsi, len
call print_string
mov rax, 60
xor rdi, rdi
syscall
; print.asm
global print_string
section .text
print_string:
mov rax, 1
mov rdx, rsi
mov rsi, rdi
mov rdi, 1
syscall
ret
Linking
List the objects after the output file. Order matters for static libraries but not for plain objects, and every referenced symbol must be defined somewhere or ld reports an undefined reference:
nasm -f elf64 -o main.o main.asm
nasm -f elf64 -o print.o print.asm
ld -o program main.o print.o
Static linking
ld links statically by default for plain objects. For libc programs, link with gcc -static to embed the C library, or leave it dynamic (the default with gcc) and let the loader resolve symbols at start.
The code on this page was assembled with NASM 3.01 and linked with GNU ld 2.45.1, and the program was run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev