An assembly program is usually divided into sections. Each section has its use: .text
is for writing
instructions, .data
is for declaring global variables.
An assembly program can be divided into multiple files. One of them should contain the _start
label. It is
the entry point, it marks the first instruction to be executed. This label should be declared global
.
global _start
section .data
msg db 'Hello World!', 0Ah ; assign msg variable with your message string
section .text
_start:
mov edx, 13 ; number of bytes to write - one for each letter plus 0Ah (line feed character)
mov ecx, msg ; move the memory address of our message string into ecx
mov ebx, 1 ; write to the STDOUT file
mov eax, 4 ; invoke SYS_WRITE (kernel opcode 4)
int 80h
mov ebx, 0 ; return 0 status on exit - 'No Errors'
mov eax, 1 ; invoke SYS_EXIT (kernel opcode 1)
int 80h
Comments start with a semicolon.
section
, global
, and db
are directives.
mov
and int
are instructions.
Save the code above as helloworld.asm. To compile and execute the assembly program, use the following commands
nasm -f elf32 helloworld.asm
ld -m elf_i386 helloworld.o -o helloworld
./helloworld
The option -f
of the NASM command is for specifying the output file format. elf32
is output format for 32-bit linux object file.
The option -m
of the ld command is for specifying machine architecture.