there are several directives provided by nasm that define constants. we have already used the equ directive in previous chapters. we will particularly discuss three directives −
- equ
- %assign
- %define
the equ directive
the equ directive is used for defining constants. the syntax of the equ directive is as follows −
constant_name equ expression
for example,
total_students equ 50
you can then use this constant value in your code, like −
mov ecx, total_students cmp eax, total_students
the operand of an equ statement can be an expression −
length equ 20 width equ 10 area equ length * width
above code segment would define area as 200.
example
the following example illustrates the use of the equ directive −
sys_exit equ 1 sys_write equ 4 stdin equ 0 stdout equ 1 section .text global _start ;must be declared for using gcc _start: ;tell linker entry point mov eax, sys_write mov ebx, stdout mov ecx, msg1 mov edx, len1 int 0x80 mov eax, sys_write mov ebx, stdout mov ecx, msg2 mov edx, len2 int 0x80 mov eax, sys_write mov ebx, stdout mov ecx, msg3 mov edx, len3 int 0x80 mov eax,sys_exit ;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
when the above code is compiled and executed, it produces the following result −
hello, programmers! welcome to the world of, linux assembly programming!
the %assign directive
the %assign directive can be used to define numeric constants like the equ directive. this directive allows redefinition. for example, you may define the constant total as −
%assign total 10
later in the code, you can redefine it as −
%assign total 20
this directive is case-sensitive.
the %define directive
the %define directive allows defining both numeric and string constants. this directive is similar to the #define in c. for example, you may define the constant ptr as −
%define ptr [ebp+4]
the above code replaces ptr by [ebp+4].
this directive also allows redefinition and it is case-sensitive.