ubuntu下的nasm汇编

安装NASM

1
$ sudo apt-get install nasm

新建文件,将其命名为test.asm,编辑并保存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
section .data
hello: db 'Hello world!',10 ; 'Hello world!' plus a linefeed character
helloLen: equ $-hello ; Length of the 'Hello world!' string
; (I'll explain soon)

section .text
global _start

_start:
mov eax,4 ; The system call for write (sys_write)
mov ebx,1 ; File descriptor 1 - standard output
mov ecx,hello ; Put the offset of hello in ecx
mov edx,helloLen ; helloLen is a constant, so we don't need to say
; mov edx,[helloLen] to get it's actual value
int 80h ; Call the kernel

mov eax,1 ; The system call for exit (sys_exit)
mov ebx,0 ; Exit with return code of 0 (no error)
int 80h

编译

1
$ nasm -f elf64 test.asm

注意,elf64只适用于64位的操作系统,对于32位的修改为elf32。

链接

1
$ ld -s -o test test.o

运行

1
$ ./test

运行结果是在屏幕上打印了“Hello,world!”,到此为止,第一个汇编程序就实现了。接下来可以编写更复杂的程序了。