使用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来测试你的程序了。


  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值