Skip to content
systemcoding.dev
Assembly

Split NASM code across files with %include

Share constants and macros between NASM 2.16.03 files with %include, and use -I with a trailing slash for an include directory.

1 min read
Summarize in AI

%include "file" pastes another file into the source at that point, so constants and macros you reuse live in one place. NASM resolves the name against the current directory and then each -I path, not against the directory of the including file, which surprises people who run nasm from a parent folder. Here a shared header defines the syscall numbers and an exit macro.

inc/sys.incnasm
SYS_exit equ 60

%macro exit 1
    mov  edi, %1
    mov  eax, SYS_exit
    syscall
%endmacro
main.asmnasm
%include "sys.inc"

global _start
section .text
_start:
    exit 7
Text
$ nasm -f elf64 -Iinc/ main.asm && ld main.o -o main
$ ./main; echo $?
7

The trailing slash on -Iinc/ is required, because NASM simply prepends the string to the file name. A %include of an already-included file defines everything twice, so start each header with %ifndef SYS_INC, %define SYS_INC and finish with %endif. Use %include for source, and incbin for raw bytes. An include is textual, so label names collide across files; keep the shared parts to equ and macros.

Also inToolchains
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.