In assembly language, different directives can be used to declare constants. The directive to be used depends on the data-type of the constant.
The three most common types of directives used to declare constants in assembly language are:
equ
%assign
%define
equ
directiveThe equ
directive is used to declare numerical constants. The value of constants declared using the equ
directive can not be changed later in code.
The following snippet of code demonstrates how to use the equ
directive to save the length of a string named message
in the data
segment of the program.
message_length equ $-message
%assign
directiveThe %assign
directive is used to numeric constants as well. However, the value of these constants may be changed later in the code.
To define a constant using %assign
, use the following syntax:
%assign bill 200
%define
directiveThe %define
directive is used to declare numeric as well as string constants. Constants declared by using this directive may be changed later in code.
The following syntax is used to define a constant using the %define
directive:
%define dollar "$"
Declaring constants is helpful when we have to use a single value over and over again. The following snippet of code stores 0x4
-the system call number of the write
system call- as a constant and assigns write_sys
as its identifier. In this way, whenever I have to call the write
system call, I can store ‘‘write_sys’’ in eax instead of ‘‘0x4’’. This makes the code more understandable.
On the other hand, it demonstrates how the equ
and %define
directives may be used in the data
segment to declare numeric and text constants.
write_sys equ 0x4segment .data:%define message0 "!" ;defines a constant stringmessage1 db "Welcome to Edpresso", message0, 0xA ;defines and concatenates a string, the constant and 0XA which is \n in hexmessage1_length equ $-message1message2 db "This is Educative", message0, 0xA ;;defines and concatenates another string, the constant and 0XA which is \n in hexmessage2_length equ $-message2segment .bss:segment .text:global _start_start:mov eax, write_sys ;4 is the unique system call number of the write system callmov ebx, 1 ;1 is the file descriptor for the stdout streammov ecx, message1 ;message is the string that needs to be printed on the consolemov edx, message1_length ;length of messageint 0x80 ;interrupt to run the kernelmov eax, write_sys ;repeats the above process tomov ebx, 1 ;print the second messagemov ecx, message2mov edx, message2_lengthint 0x80mov eax, 0x1 ;1 is the unique system call number of the exit system callmov ebx, 0 ;argument to exit system callint 0x80 ;interrupt to run the kernel and exit gracefully
Free Resources