Calling C functions
EXTERN and linking
EXTERN declares a symbol defined in another object, like a libc function. Link against libc with gcc, which adds the startup code and the dynamic linker flags:
extern printf
section .data
fmt db "printf says %ld", 10, 0
section .text
global main
main:
push rbp ; keep RSP 16-byte aligned
mov rdi, fmt
mov rsi, 42
xor eax, eax
call printf wrt ..plt
pop rbp
xor eax, eax
ret
Assemble the file with nasm and link it with gcc: main returns to the C startup code, and the pushed RBP keeps RSP 16-byte aligned for the call.
nasm -f elf64 -o print.o print.asm
gcc -no-pie -o print print.o
The System V ABI
Integer arguments go in RDI, RSI, RDX, RCX, R8, R9; floating-point arguments in XMM0-XMM7; the return value in RAX (or XMM0). AL must hold the number of vector registers used when calling a variadic function like printf:
mov rdi, fmt
mov rsi, rcx
xor eax, eax ; zero vector regs for printf
call printf wrt ..plt
A printf example
The wrt ..plt suffix routes the call through the procedure linkage table, which the dynamic linker fills in. For a program that only uses syscalls, plain ld works; with libc, link with gcc instead.
The code on this page was assembled with NASM 3.01 and linked with gcc 15.2.0, and the program was run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev