使用NASM和CL(或LINK)写HelloWorld

原文地址:http://www.tech-juice.org/2011/02/26/assembler-tutorial-hello-world-with-nasm-and-cl-exe-or-link-exe/


前言

...


编译汇编代码

我们来编译链接这个名为helloworld.asm的汇编代码

; This is a Win32 console program that writes "Hello, World" on one line and
; then exits.  It needs to be linked with a C library.
 
global  _main
extern  _printf
 
section .text
_main:
push    message
call    _printf
add     esp, 4
ret
message:
db      'Hello, World', 10, 0
正如你所看到的我们使用printf来打印出Hello, World。这个函数使用了extern,因为它是导入函数(它属于C运行时库)。

Paul Carter的教程中提供了用于编译例子代码的命令

; To assemble for Microsoft Visual Studio
 
; nasm -f win32 -d COFF_TYPE asm_io.asm

遗憾的是语法错误。-d开关似乎在NASM2.09.04版本中被废弃,它不起任何作用。表示文件类型的win32看上去是没问题的(它表示文件输出格式为win32)。

正确的编译helloworld.asm的命令如下:

nasm -f win32 helloworld.asm
使用以上命令NASM生成一个名为helloworld.obj的文件。现在我们要使用链接器将.obj文件链接到.exe文件中。打开Visual Studio Command Prompt然后输入如下内容:

link.exe helloworld.obj libcmt.lib
 
// or
 
cl.exe helloworld.obj /link libcmt.lib
printf()函数通过libcmt.lib(此库属于C运行时库)被静态包含。如果你省略了libcmt.lib的话你将得到错误error LNK2001: unresolved external symbol _printf


现在你可以执行helloworld.exe来测试你的程序了。


猜你喜欢

转载自blog.csdn.net/duweix/article/details/19911967
cl