10.6. Our First Program
前一頁 | 章 10. x86 Assembly Language Programming | 下一頁

## 10.6. Our First Program

We are now ready for our first program, the mandatory Hello, World!

1: %include 'system.inc' 2: 3: section .data 4: hello db 'Hello, World!', 0Ah 5: hbytes equ $-hello 6: 7: section .text 8: global _start 9: _start: 10: push dword hbytes 11: push dword hello 12: push dword stdout 13: sys.write 14: 15: push dword 0 16: sys.exit

Here is what it does: Line 1 includes the defines, the macros, and the code from `system.inc`.

Lines 3-5 are the data: Line 3 starts the data section/segment. Line 4 contains the string "Hello, World!" followed by a new line (`0Ah`). Line 5 creates a constant that contains the length of the string from line 4 in bytes.

Lines 7-16 contain the code. Note that FreeBSD uses the elf file format for its executables, which requires every program to start at the point labeled `_start` (or, more precisely, the linker expects that). This label has to be global.

Lines 10-13 ask the system to write `hbytes` bytes of the `hello` string to `stdout`.

Lines 15-16 ask the system to end the program with the return value of `0`. The `SYS_exit` syscall never returns, so the code ends there.

### 注意:

If you have come to UNIX® from MS-DOS® assembly language background, you may be used to writing directly to the video hardware. You will never have to worry about this in FreeBSD, or any other flavor of UNIX®. As far as you are concerned, you are writing to a file known as `stdout`. This can be the video screen, or a telnet terminal, or an actual file, or even the input of another program. Which one it is, is for the system to figure out.

### 10.6.1. Assembling the Code

Type the code (except the line numbers) in an editor, and save it in a file named `hello.asm`. You need nasm to assemble it.

#### 10.6.1.1. Installing nasm

If you do not have nasm, type:

`%` `su` Password:``your root password`` `#` `cd /usr/ports/devel/nasm` `#` `make install` `#` `exit` `%`

You may type `make install clean` instead of just `make install` if you do not want to keep nasm source code.

Either way, FreeBSD will automatically download nasm from the Internet, compile it, and install it on your system.

### 注意:

If your system is not FreeBSD, you need to get nasm from its home page. You can still use it to assemble FreeBSD code.

Now you can assemble, link, and run the code:

`%` `nasm -f elf hello.asm` `%` `ld -s -o hello hello.o` `%` `./hello` Hello, World! `%`

前一頁 | 上一層 | 下一頁
10.5. Creating Portable Code | 起始頁 | 10.7. Writing UNIX® Filters

本文及其他文件，可由此下載： ftp://ftp.FreeBSD.org/pub/FreeBSD/doc/。

若有 FreeBSD 方面疑問，請先閱讀 FreeBSD 相關文件，如不能解決的話，再洽詢 <questions@FreeBSD.org>。
關於本文件的問題，請洽詢 <doc@FreeBSD.org>。