0
0
Cnc-programmingHow-ToBeginner · 4 min read

How to Compile ARM Assembly Code: Step-by-Step Guide

To compile ARM assembly code, write your code in a .s file, then use the GNU assembler as to assemble it into an object file. Finally, link the object file with ld or use gcc to produce an executable.
📐

Syntax

To compile ARM assembly code, you typically use these commands:

  • as input.s -o output.o: Assembles the ARM assembly source file input.s into an object file output.o.
  • ld output.o -o executable: Links the object file to create an executable named executable.
  • gcc input.s -o executable: Combines assembling and linking in one step using GCC.

Each part:

  • as: GNU assembler for ARM.
  • ld: GNU linker to create executable.
  • gcc: Compiler driver that can assemble and link.
  • input.s: Your ARM assembly source file.
  • output.o: Object file after assembling.
  • executable: Final runnable program.
bash
as input.s -o output.o
ld output.o -o executable
gcc input.s -o executable
💻

Example

This example shows a simple ARM assembly program that returns 42 as the exit code. It demonstrates assembling and linking using gcc.

armasm
.global _start
_start:
    mov r0, #42      @ Set return code 42
    mov r7, #1       @ syscall number for exit
    svc 0            @ make syscall
Output
echo $? 42
⚠️

Common Pitfalls

Common mistakes when compiling ARM assembly code include:

  • Using the wrong file extension (use .s for assembly source).
  • Forgetting to declare global entry point with .global _start.
  • Not linking the object file, resulting in no executable.
  • Using as without linking, so no runnable program is created.
  • Mixing ARM and Thumb instructions without proper flags.

Example of wrong and right way:

bash
# Wrong: assembling only, no linking
as input.s -o output.o
./output.o  # Error: not executable

# Right: assemble and link
as input.s -o output.o
ld output.o -o executable
./executable  # Runs correctly
📊

Quick Reference

CommandDescription
as input.s -o output.oAssemble ARM assembly source to object file
ld output.o -o executableLink object file to create executable
gcc input.s -o executableAssemble and link in one step
file executableCheck file type and architecture
echo $?Check exit code of last program

Key Takeaways

Use as to assemble ARM assembly source into an object file.
Link the object file with ld or use gcc to create an executable.
Always declare a global entry point like _start in your assembly code.
Use the .s extension for ARM assembly source files.
Check your executable's exit code to verify correct program behavior.