0
0
Cnc-programmingHow-ToBeginner · 4 min read

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 .global or .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 syscall
💻

Example

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 exit
Output
Program exits with code 15 (sum of 5 + 10)
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting to declare .global _start so the linker knows the entry point.
  • Using wrong syscall numbers or forgetting to set R7 before SWI 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 0
📊

Quick Reference

InstructionDescriptionExample
MOVMove immediate or register valueMOV R0, #1
ADDAdd two registersADD R0, R0, R1
SUBSubtract registersSUB R0, R1, R2
SWISoftware interrupt for syscallSWI 0
.globalDeclare global symbol.global _start
.textStart 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.