How to Write ARM Assembly Program: Syntax and Example
To write an ARM assembly program, use
ARM assembly instructions with a clear syntax including labels, instructions, and directives. Start with a _start label, write instructions like MOV or ADD, and end with a system call to exit the program.Syntax
An ARM assembly program consists of labels, instructions, and directives. Labels mark positions in code. Instructions perform operations like moving data or arithmetic. Directives tell the assembler how to organize the program.
Basic syntax parts:
- Label: A name followed by a colon, e.g.,
_start: - Instruction: Operation with operands, e.g.,
MOV R0, #1 - Directive: Assembler commands like
.globalor.text
armasm
.global _start
.text
_start:
MOV R0, #1 @ Move 1 into register R0
MOV R1, #2 @ Move 2 into register R1
ADD R0, R0, R1 @ Add R0 and R1, store in R0
MOV R7, #1 @ Prepare to exit (syscall number 1)
SWI 0 @ Make syscallExample
This example adds two numbers and exits the program. It shows how to use registers, instructions, and a system call to end the program.
armasm
.global _start
.text
_start:
MOV R0, #5 @ Load 5 into R0
MOV R1, #10 @ Load 10 into R1
ADD R0, R0, R1 @ Add R0 and R1, result in R0
MOV R7, #1 @ Syscall number for exit
SWI 0 @ Make syscall to exitOutput
Program exits with code 15 (sum of 5 + 10)
Common Pitfalls
Common mistakes include:
- Forgetting to declare
.global _startso the linker knows the entry point. - Using wrong syscall numbers or forgetting to set
R7beforeSWI 0. - Mixing up immediate values and registers (immediate values need a
#prefix). - Not aligning data or code sections properly.
Example of wrong and right usage:
armasm
@ Wrong: missing .global and wrong syscall
.text
_start:
MOV R0, #0
SWI 0
@ Right:
.global _start
.text
_start:
MOV R0, #0
MOV R7, #1
SWI 0Quick Reference
| Instruction | Description | Example |
|---|---|---|
| MOV | Move immediate or register value | MOV R0, #1 |
| ADD | Add two registers | ADD R0, R0, R1 |
| SUB | Subtract registers | SUB R0, R1, R2 |
| SWI | Software interrupt for syscall | SWI 0 |
| .global | Declare global symbol | .global _start |
| .text | Start code section | .text |
Key Takeaways
Start ARM assembly programs with a global _start label and .text directive.
Use MOV, ADD, and SWI instructions to manipulate data and make system calls.
Always set the syscall number in R7 before calling SWI 0 to exit.
Immediate values require a # prefix, and labels must end with a colon.
Check for proper directives and register usage to avoid common errors.