How to compile assembly code with NASM

Compiling assembly code involves translating human-readable assembly code into machine code or object code that a computer can execute.

Compilation Process

  1. Assembler: The first step is to use an assembler to convert assembly code into machine code or object code. Assemblers are specific to the architecture of the target machine.
  2. Linker: If the program consists of multiple source files or relies on external libraries, a linker may be used to combine these files into a single executable. The linker resolves addresses and references between different parts of the code.
Example

Consider a simple x86 assembly program that prints "Hello, World!" to the console:

section .data msg db 'Hello, World!', 0 section .text global _start _start: ; write the message to stdout mov eax, 4 ; system call number for sys_write mov ebx, 1 ; file descriptor 1 is stdout mov ecx, msg ; pointer to the message mov edx, 13 ; length of the message int 0x80 ; call kernel ; exit the program mov eax, 1 ; system call number for sys_exit xor ebx, ebx ; exit code 0 int 0x80 ; call kernel

Assembling

Use an assembler (e.g., NASM for x86) to convert the assembly code into object code:

nasm -f elf32 hello.asm -o hello.o

This produces an object file (hello.o) containing machine code.

Linking

If needed, use a linker (e.g., ld for Linux) to link the object file with any necessary libraries:

ld -m elf_i386 -s -o hello hello.o

This produces the final executable (hello), ready to be executed.

Execution

Run the compiled executable:

./hello

The program will execute and print "Hello, World!" to the console.

Conclusion

Compiling assembly code involves using an assembler to convert human-readable assembly code into machine code or object code, and optionally using a linker to combine multiple object files into a single executable.