Q: What is a macro?
A: A macro is a small piece of code that be reused later.
\\
Q: How do I create one in ASM?
A: Here is an example of a macro to exit the program:
%macro exitProgram
mov eax, 1
mov ebx, 0
int 0x80
%endmacro
Macro start with %macro followed by the name of the macro. Then the macro's code. To end the macro you use %endmacro.
\\
Q: Where do I put the macro in my ASM file?
A: Macros are typically placed in the segment .bss section of the program.
segment .bss
%macro exitProgram
mov eax, 1
mov ebx, 0
int 0x80
%endmacro
\\
Q: How do I call a macro?
A: To call our exitProgram from before macro, we just use the name of the macro as it's call.
_start:
enter 0, 0
pusha
[some code]
exitProgram
popa
leave
hlt
\\
Q: Can I pass information to a macro?
A: Sure, you just define how many parameters are going to be passed right after the name of the macro. These values would then be accessed inside the macro using % followed by the number corresponding to it's place in the passed parameters list, starting from 1.
%macro print 2
mov eax, 0x4
mov ebx, 0x1
mov ecx, %1
mov edx, %2
%endmacro
This could then be called using:
print msg1, msg1len
As a result, the contents of msg1, of length defined by msg1len would be displayed to stdout.
\\
Q: Can a macro make use of another macro?
A: It sure can. Just call it inside of the macro like you would in your program.
segment .data
newline db 0xA, 0x0
segment .bss
%macro printNewline
print newline, 0x2
%endmacro
\\
Q: Is possible to put a whole bunch of macros into an external file and include them in multiple programs?
A: Yes, you would use the %include directive at the top of your asm file. Typically macro files will use a .mac extension.
%include "myMacros.mac"
Your macro file would then have a segment .bss section with your macro definitions:
segment .bss
%macro exitProgram
mov eax, 1
mov ebx, 0
int 0x80
%endmacro
%macro print 2
mov eax, 0x4
mov ebx, 0x1
mov ecx, %1
mov edx, %2
%endmacro
Q: Can I include multiple macro files?
A: Just use another %include statement.
%include "file1.mac"
%include "file2.mac"