Macros
Defining a macro
A macro is a text template the assembler expands at assembly time. %macro names it and gives the parameter count, %endmacro closes it:
%macro WRITE 2
mov rax, 1
mov rdi, 1
mov rsi, %1
mov rdx, %2
syscall
%endmacro
WRITE msg, len
Parameters
Parameters are %1 through %n. The assembler pastes them into the template as text, so they can be registers, constants, or expressions:
%macro ADD3 3
mov rax, %1
add rax, %2
add rax, %3
%endmacro
ADD3 10, 20, 30 ; rax = 60
Local labels
Labels inside a macro expand once per use, which clashes. The %% prefix makes a label local to one expansion, so two calls of the same macro never see each other's labels. NASM assembles %%loop into a unique label for every call.
%macro COUNTDOWN 1
mov rcx, %1
%%loop:
dec rcx
jnz %%loop
%endmacro
COUNTDOWN 5
COUNTDOWN 3
The code on this page was assembled with NASM 3.01 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev