Macros are used to make programs written in assembly code modular and concise.
Macros are very similar to procedures but follow a different syntax and accept parameters.
Macros are very similar to functions that are available in most high-level programming languages.
A procedure is a feature of Assembly Language that enables programmers to make assembly code modular. Unlike procedures,
macrosare defined outside of the
textsegment, accept parameters, and are primarily used to create small modules.
We can declare a
macro using the following syntax:
%macro macro_name parameter_count instr#1 instr#2 ... ... instr#n-1 instr#n %endmacro
The program below demonstrates how a
macro may print a string on the console:
We define three strings and their sizes in the data segment. Our
macro takes in 2 parameters, the message that needs to be printed and its size, and contains the instructions needed to write to the
stdout stream. The
macro is called thrice to print each of the three strings. If a
macro was not used, we would have to write all the instructions inside the
macro thrice in the text segment. In this way, using
macros helps us make our code modular and shorter in size.
%macro print 2 mov edx, %1 ;length of message or the first argument stored in edx mov ecx, %2 ;message to be printed or the second argument stored in ecx mov ebx, 1 ;ebx contains the file descriptor of the file descriptor (1 for stdout) mov eax, 4 ;eax contains the system call number. 4 is the system call number for the write system call int 0x80 ;kernel interrupts to execute the write system call in kernel mode %endmacro ;returns to the address where the print procedure was last called section .text global _start _start: print len0, msg0 ;executes our macro with len0 and msg0 as the first and second arguments, respectively print len1, msg1 ;executes our macro with len1 and msg1 as the first and second arguments, respectively print len2, msg2 ;executes our macro with len2 and msg2 as the first and second arguments, respectively mov eax, 1 ;system call number for the exit system call saved in eax int 0x80 ;kernel interrupt to shift from user mode to kernel mode to execute the system call section .data msg0 db "Welcome to Educative!", 0x0A ;defines message to be printed. 0xA is \n in hex. len0 equ $ - msg0 ;stores length of the message msg1 db "We are glad to have you here.", 0x0A ;defines message to be printed. 0xA is \n in hex. len1 equ $ - msg1 ;stores length of the message msg2 db "You are almost an expert at assembly language now!", 0x0A ;defines message to be printed. 0xA is \n in hex. len2 equ $ - msg2 ;stores length of the message segment .bss
View all Courses