Advanced macros and %include
%include
%include pastes another file into the source at assembly time. Put shared constants and macros in one file and include it wherever they are needed:
%include "consts.inc" %include "macros.inc"
%define
%define names a constant or a simple macro. Case matters: %define and %idefine differ, and %xdefine re-expands at definition time. Use it for syscall numbers and struct offsets:
%define SYS_EXIT 60 %define PTR_SIZE 8 %define BUF_END buf + BUF_LEN
%if and friends
The preprocessor has conditionals: %if, %ifdef, %elif, %else, %endif. They test assembly-time values, so one source can build with or without debug code:
%ifdef DEBUG mov rdi, debug_msg call print_string %endif
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
%include "consts.inc"do?Answer
It pastes the file into the source at assembly time
The preprocessor reads the file and inserts its text before assembly.
-
How does %define differ from a macro built with %macro?
Answer
%define makes a one-line substitution, %macro a parameterised template
A %define is a simple name or one-line body; %macro has parameters and a body with an end marker.
-
Which directive makes a name match regardless of case?
Answer
%idefine
The i in %idefine means case-insensitive.
-
What is the difference between %define and %xdefine?
Answer
%xdefine expands its value at definition time
A single-line macro normally expands when it is used; %xdefine fixes the expansion earlier.
-
What does
%ifdef DEBUGtest?Answer
Whether the symbol DEBUG is defined
The condition is an assembly-time test of the preprocessor symbol.
-
When do %if blocks disappear from the program?
Answer
At assembly time, when the condition is false
The preprocessor chooses the text before the assembler sees it.
-
Where does NASM look for a file named by %include?
Answer
In the current folder and the -I include path
The source folder comes first, and -I adds folders to the search.
-
What does
%define BUF_END buf + BUF_LENdefine?Answer
A one-line macro that expands to the expression
The body is text, so every use is replaced by buf + BUF_LEN.
-
Which pair closes a conditional block?
Answer
%if ... %endif
%if, %elif, %else and %endif form the conditional block.
-
What does
%define SYS_EXIT 60cost at run time?Answer
Nothing: it is gone after assembly
The name is replaced by the number in the source, so no code is generated for it.
The snippets on this page are fragments, not whole programs: they show the preprocessor forms. They were assembled with NASM 3.01 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev