使用NASM和CL(或LINK)写HelloWorld

时间:2019-03-25
本文章向大家介绍使用NASM和CL(或LINK)写HelloWorld,主要包括使用NASM和CL(或LINK)写HelloWorld使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

编译汇编代码

我们来编译链接这个名为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.objhttp://yuanzunnovel.com的文件。现在我们要使用链接器将.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来测试你的程序了。