本文分为以下三个部分:
1)用Visual Studio2008建立一个汇编控制台工程
2)汇编程序模板
3)汇编编写的Hello World程序
用Visual Studio2008建立一个汇编控制台工程
打开Visual Studio 2008,创建一个C++空工程
在工程中添加一个.asm文件:
在solution Explorer上点击右键,选择Add->New Item
选择C++文件,把其命名为.asm结尾的文件.
打开主菜单上的Project->Custom Build Rule。 勾选Microsoft Macro Assembler
在主菜单选择Project->Properties,在打开的对话框左侧菜单中选择Configuration Properties->Linker->System,在右侧SubSystem栏中选择Console(/SUBSYSTEM:CONSOLE)
如果代码中引用了非默认路径下的头文件,需要添加头文件路径:在主菜单中选择Project->Properties,在打开的对话框左侧菜单中选择Configuration Properties->Microsoft Macro Assembler->General,在右侧Include Paths栏中添加头文件文件夹。
如果需要添加额外的链接库,在主菜单选择Project->Properties,在打开的对话框左侧菜单中选择Configuration Properties->Linker->Input,在右侧Additional Dependencies中键入链接库名。
如果要添加的链接库不在默认路径下,需要添加链接库路径:在主菜单选择Project->Properties,在打开的对话框左侧菜单中选择Configuration Properties->Linker->General,在右侧Additional Library Directories栏中键入链接库目录名。
好了,我们已经配置好编译环境,接下来的事就是写我们的第一个汇编程序。
汇编程序模板
我们编写汇编程序时,不用每次都从头写起,可以把程序的框架保存起来,每次编写汇编时复制张贴做细微修改即可,下面即是一个框架代码:
TITLE It is a
template
.386
.MODEL flat,stdcall
ExitProcess PROTO, dwExitCode:
DWORD
;include Irvine.inc
.data
input
BYTE
"Hello World"
,0
Len
DWORD
$-input-1
.code
main PROC
mov eax,1
INVOKE ExitProcess,0
main ENDP
END main
|
我们简单的分析一下这段代码:
1).386表示这是一个x86汇编程序
2).MODEL flat,stdcall. flat表示采用平坦分段模式,stdcall指使用INVOKE伪指令时,采用stdcall调用模式,因为Windows API函数是使用stdcall的。
3)ExitProcess PROTO, dwExitCode:DWORD ,这是一个函数声明,ExitProcess是一个Windows API函数,用于退出进程。函数的声明也可以包括在.inc头文件中,通过如include Irvine.inc 命令引用头文件。
4).data表示数据段开始,.code为代码段开始。
5)在主程序通过调用INVOKE ExitProcess,0 来退出进程。
在32位汇编编程中,不再使用系统中断命令,而是通过Windows API来进行IO调用。要使用Windows API程序,需要在汇编代码或者.inc头文件中对要使用的API函数进行声明,编译时要链接链接库kernel32.lib (工程默认会链接该链接库,在Linker->Input->Additional Dependencies,可以查看是否包含此链接库)
汇编编写的Hello World程序
该程序在控制台上打印“Hello World”:
TITLE HelloWorld
.386
.MODEL flat,stdcall
GetStdHandle PROTO, ; get standard handle
nStdHandle:
DWORD
; type of console handle
STD_OUTPUT_HANDLE EQU -11 ; predefined Win API constant
WriteConsole EQU <WriteConsoleA>
WriteConsole PROTO, ; write a buffer to the console
outHandle:
DWORD
, ; output handle
pBuffer:PTR
BYTE
, ; pointer to buffer
bufsize:
DWORD
, ; size of buffer
pCount:PTR
DWORD
, ; ptr to number of bytes written
pReserved:
DWORD
; (not used)
ExitProcess PROTO, dwExitCode:
DWORD
.data
input
BYTE
"Hello World"
,0
Len
DWORD
$-input-1
handle
DWORD
?
actualWrite
DWORD
?
.code
main PROC
INVOKE GetStdHandle,STD_OUTPUT_HANDLE
mov handle,EAX
INVOKE WriteConsole,handle,OFFSET input,Len,OFFSET actualWrite,0
INVOKE ExitProcess,0
main ENDP
END main
|
参考
http://timerover.infor.org/Masm615/INCLUDE/SmallWin.inc
Intel汇编语言程序设计(第四版),Kip R.Irvine
http://msdn.microsoft.com/en-us/library/ms687401(VS.85).aspx
http://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx
声明
本文为Binhua Liu原创作品。本文允许复制,修改,传递,但不允许用于商业用途。转载请注明出处。本文发表于2010年7月13日。