Assembly Macro - Definition, Syntax and Examples
Macros: A macro is a set of instructions that is defined once and can then be used multiple times in a program. If instructions have to be used repeatedly for a particular task, a code block is made of a group of those instructions which are called and used at the time of need. This is called macros.
Another way to ensure modular programming in assembly language is to write macros. A macro is a sequence of instructions, which is specified by a name and can be used anywhere in the program.
macro Syntax
In NASM, macros are defined with the %macro and %endmacro directives. Macros begin with the %macro directive and end with the %endmacro directive.
Syntax for macro definition -
%macro macro_name number_of_params
macro body
%endmacro
Where, number_of_params specifies the number of parameters, macro_name specifies the name of the macro.
The macro is invoked using the macro name with the required parameters. When you need to use some sequence of instructions many times in a program, you can put those instructions in a macro and use it instead of typing the instructions every time.
For example, a very common requirement for programs is to write a string of characters to the screen. To display a string of characters, you need the following sequence of instructions −
mov edx,len ;message length
mov ecx,msg ;message to write
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
In the above example of displaying a character string, the registers EAX, EBX, ECX, and EDX are used by the INT 80H function call. Therefore, every time you need to display on the screen, you need to save these registers on the stack, invoke INT 80H, and then restore the original value of the registers from the stack. Therefore, it may be useful to write two macros to save and restore the data.
We have seen that, some instructions like IMUL, IDIV, INT, etc require some information to be stored in some specific registers and even return values in some specific registers. If the program was already using those registers to hold important data, the existing data in these registers must be saved to the stack and restored after the instruction is executed.
Macros Exampal
The following example shows how to define and use macros −
; A macro with two parameters
; Implements the write system call
%macro write_string 2
mov eax, 4
mov ebx, 1
mov ecx, %1
mov edx, %2
int 80h
%endmacro
section .text
global _start ;must be declared for using gcc
_start: ;tell linker entry point
write_string msg1, len1
write_string msg2, len2
write_string msg3, len3
mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
msg1 db 'Hello, programmers!',0xA,0xD
len1 equ $ - msg1
msg2 db 'Welcome to the world of,', 0xA,0xD
len2 equ $- msg2
msg3 db 'Linux assembly programming! '
len3 equ $- msg3
result −
Hello, programmers!
Welcome to the world of,
Linux assembly programming!