彙編 - 常量



NASM 提供了一些用於定義常量的指令。我們已經在前面的章節中使用過 EQU 指令。我們將特別討論三個指令:

  • EQU
  • %assign
  • %define

EQU 指令

EQU 指令用於定義常量。EQU 指令的語法如下:

CONSTANT_NAME EQU expression

例如:

TOTAL_STUDENTS equ 50

然後你可以在你的程式碼中使用這個常量值,例如:

mov  ecx,  TOTAL_STUDENTS 
cmp  eax,  TOTAL_STUDENTS

EQU 語句的運算元可以是表示式:

LENGTH equ 20
WIDTH  equ 10
AREA   equ length * width

以上程式碼段將 AREA 定義為 200。

示例

以下示例說明了 EQU 指令的使用:

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

當以上程式碼編譯並執行時,會產生以下結果:

Hello, programmers!
Welcome to the world of,
Linux assembly programming!

%assign 指令

%assign 指令可以像 EQU 指令一樣用於定義數字常量。此指令允許重新定義。例如,您可以定義常量 TOTAL 為:

%assign TOTAL 10

在程式碼的後面,您可以將其重新定義為:

%assign  TOTAL  20

此指令區分大小寫。

%define 指令

%define 指令允許定義數字和字串常量。此指令類似於 C 語言中的 #define。例如,您可以定義常量 PTR 為:

%define PTR [EBP+4]

以上程式碼將 PTR 替換為 [EBP+4]。

此指令也允許重新定義,並且區分大小寫。

廣告