Topics / C Programming / Q31
What are the stages of compilation in C?
Short answer: There are four stages. Preprocessing expands #include, macros and conditional compilation. Compilation translates the preprocessed C into assembly. Assembly turns that into a relocatable object file (.o). Linking combines object files and libraries, resolves symbols, and places code and data at addresses defined by the linker script, producing an executable (ELF).
arm-none-eabi-gcc -E main.c -o main.i # 1. preprocess
arm-none-eabi-gcc -S main.i -o main.s # 2. compile to assembly
arm-none-eabi-gcc -c main.s -o main.o # 3. assemble to object file
arm-none-eabi-gcc main.o uart.o -T stm32.ld -o firmware.elf # 4. link
arm-none-eabi-objcopy -O binary firmware.elf firmware.bin # for flashing
arm-none-eabi-objcopy -O ihex firmware.elf firmware.hex
What each stage produces and checks
| Stage | Output | Errors you see |
|---|---|---|
| Preprocessor | .i (pure C, no # lines except line markers) |
missing header, bad macro |
| Compiler | .s assembly |
syntax and type errors, warnings |
| Assembler | .o with sections (.text, .data, .bss, .rodata), a symbol table and relocations |
rare (invalid inline assembly) |
| Linker | .elf (plus a .map file with -Wl,-Map=...) |
undefined reference, multiple definition, region FLASH overflowed |
Useful inspection tools: nm (symbols), objdump -d (disassembly), readelf -S (sections), size (text/data/bss sizes), and the map file, which shows where every function and variable ended up and how much flash and RAM is used.
Embedded specifics
- The linker script (
.ld) defines the memory regions (FLASH, RAM) and where each section goes. - The start-up code (often
startup_xxx.s) is linked in and runs beforemain. -ffunction-sections -fdata-sectionsplus-Wl,--gc-sectionslet the linker remove unused functions, which saves a lot of flash.- LTO (
-flto) does optimisation across files at link time.