Chapter 4 - Introduction to Programming in NASM
Now that we have gone through all the basics required for creating a program, let's begin. Like all programming lessons, we will first learn how to create a Hello World program. Programming in NASM is easy if you understand how each construct is used and implemented. A transition from C like language can be frustrating at first, but let's take it step by step. We will learn to program by translating code snippets in C language to assembly code.
Hello World Program
As discussed earlier, the whole program is divided into 3 sections, namely code section (section .text), section for uninitalised variables (section .bss) and section for initialised variables (section .text).
section .text is the place from where the execution starts in NASM program,
analogous to the main() function in C-Programming.
-
Let's store the string "Hello World" into a variable named str. We are going to print that string as the output
Pseudo Code:
char str[13] = "Hello World";
NASM Code:
NB: Using equ we declare constants, ie. their value won’t change during execution. $-string will return the length of string variables in bytes (ie. number of characters)
-
Now we need to print this variable onto the screen. For that we use the write system call.
Pseudo Code:
printf("%s",str);
NASM Code:
-
Now since we have printed the text, let's exit the program. We use the exit system call for the same
Pseudo Code:
return 0;
NASM Code:
-
section .text is the place from where the execution starts in NASM program, analogous to the main() function in C-Programming. So let's put the print and exit parts into the section.
The final program looks like this: