对宏的再认识
2008-10-14 09:35:03 来源:WEB开发网宏的概念对我来说并不陌生,可是我从不使用宏,而总是使用过程(子程序),因为我觉得宏会使程序变长,虽然它在执行时会比调用子程序快。所以一直对宏不太感冒,直到在看老罗的程序时发现一个有用的宏,它使程序的编写更简炼、直观,并且超出了我想象中的概念,因此我觉得有必要对宏进行再认识。
下面是个小程序,功能很简单,不过含有一个宏:
------------------------------------------------------------------------
文件名:20-1.ASM
include windows.inc
include kernel32.inc
include user32.inc
includelib kernel32.lib
includelib user32.lib
CTEXT MACRO y:VARARG
LOCAL sym
CONST segment
ifidni ,<>
sym db 0
else
sym db y,0
endif
CONST ends
exitm
ENDM
.code
Start:
invoke MessageBoxA,NULL,CTEXT("Hello, world !"),CTEXT("Hi!"),MB_ICONINFORMATION
invoke ExitProcess,NULL
end Start
---------------------------------------------------------------------------
编译时增加一个开关项 /EP,作用是Output preprocessed listing to stdout,我们将其改向输出到 L.txt
D:\MASM7>ml /c /coff /I include /EP 20-1.asm > L.txt
Microsoft (R) Macro Assembler Version 6.14.8444
Copyright (C) Microsoft Corp 1981-1997. All rights reserved.
D:\MASM7>_
---------------------------------------------------------------------------
查看L.txt文件的内容,这是预处理后的内容,注意宏的展开情况:
.386
.model flat, stdcall
option casemap:none
. ;这块内容很多,都是.inc文件中的定义、声明等,此处略
.
.
includelib kernel32.lib
includelib user32.lib
.code
Start:
CONST segment
??0019 db "Hello, world !",0
CONST ends
CONST segment
??001A db "Hi!",0
CONST ends
invoke MessageBoxA,NULL,offset ??0019,offset ??001A,MB_ICONINFORMATION
invoke ExitProcess,NULL
end Start
看了以后,心里是否清楚一些内容?,然后向过去一样将其生成20-1.exe
---------------------------------------------------------------------------
再看一下这个文件,文件名20-2.asm
.386
.model flat, stdcall
option casemap:none
include windows.inc
include kernel32.inc
include user32.inc
includelib kernel32.lib
includelib user32.lib
.const
xx db "Hello, world !",0
yy db "Hi!",0
.code
Start:
invoke MessageBoxA,NULL,addr xx,addr yy,MB_ICONINFORMATION
invoke ExitProcess,NULL
end Start
---------------------------------------------------------------------------
将上面的文件生成可执行文件20-2.exe,我们作个比较:
D:\MASM7>fc 20-1.exe 20-2.exe /b
Comparing files 20-1.exe and 20-2.exe
000000B8: BD BF
000000B9: 00 03
文件没有任何的不同。哦,上面不同的是文件的 TimeDateStamp,即生成文件的时间,不影响什么!
---------------------------------------------------------------------------
再看下面的程序,文件名:20-3.asm,将由它产生20-3.exe文件,运行结果一样,但程序结构不同(参后)
.386
.model flat, stdcall
option casemap:none
include windows.inc
include kernel32.inc
include user32.inc
includelib kernel32.lib
includelib user32.lib
.code
Start:
cc segment
xx db "Hello, world !",0
cc ends
cc segment
yy db "Hi!",0
cc ends
invoke MessageBoxA,NULL,addr xx,addr yy,MB_ICONINFORMATION
invoke ExitProcess,NULL
end Start
---------------------------------------------------------------------------
更多精彩
赞助商链接