目录

汇编 - 常量

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。

例子 (Example)

以下示例说明了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指令允许定义数字和字符串常量。 该指令类似于C中的#define。例如,您可以将常量PTR定义为 -

%define PTR [EBP+4]

上面的代码用[EBP + 4]替换PTR

该指令还允许重新定义,并且区分大小写。

↑回到顶部↑
WIKI教程 @2018