Macros in NASM

Because assemblers are line-oriented, there's often a difference between single-line and multi-line macros.

In NASM, "%define" is for single-line macros, such as renaming registers.  It works very much like C/C++ "#define".

%define param rdi 
add param,1
mov rax,param
ret

(Try this in NetRun now!)

You can also rename instructions, such as adding the missing "e" to "move":

%define move mov 
add rdi,1
move rax,rdi
ret

(Try this in NetRun now!)

As with C/C++, you can cross between instruction and register, and include arbitrary syntax like commas inside the macro body:

%define mover mov rax,
add rdi,1
mover rdi
ret

(Try this in NetRun now!)

For multi-line macros, which can expand out to several instructions, an entirely different syntax is used.  This is normally used to create new pseudo-instructions, such as this new "return" operation.  The first 1 is the number of parameters expected; the %1 refers to the first macro parameter.

; Make a multi-line macro named "return", working like C/C++
;   See http://www.nasm.us/doc/nasmdoc4.html#section-4.3
%macro return 1
	mov rax,%1
	ret
%endmacro

return 3;

(Try this in NetRun now!)


CS 301 Lecture Note, 2014, Dr. Orion LawlorUAF Computer Science Department.