Macros are reusable blocks of code that are substituted during assembly. They simplify repetitive tasks and improve code readability.
Macros are defined using the %macro directive, and invoked like regular instructions.
%macro macro_name num_params
; Macro body
%endmacro
This macro writes a string to the screen using a system call.
%macro write_string 2
mov rax, 1 ; System call: write
mov rdi, 1 ; File descriptor: stdout
mov rsi, %1 ; String address
mov rdx, %2 ; String length
syscall
%endmacro
section .data
msg db 'Hello, Macro!', 0xA
len equ $ - msg
section .text
global _start
_start:
write_string msg, len ; Call the macro
mov rax, 60 ; System call: exit
xor rdi, rdi ; Exit code: 0
syscall
This macro adds two numbers and stores the result in a register.
%macro add_two_numbers 3
mov %1, %2 ; Move the first number to the target register
add %1, %3 ; Add the second number
%endmacro
section .text
global _start
_start:
add_two_numbers rax, 5, 10 ; Adds 5 and 10, stores the result in rax
mov rax, 60 ; System call: exit
xor rdi, rdi ; Exit code: 0
syscall