Try Embedded

The compilation pipeline

Preprocessor, compiler, assembler and linker, and what each one produces.

Four tools behind one command

arm-none-eabi-gcc main.c -o main.elf looks like one step. It is four programs run in sequence, each producing a file the next one reads. Knowing the stages tells you which tool produced an error and where to look.

StageToolInputOutputTypical errors
Preprocesscpp (via gcc -E).c and headersOne expanded translation unit (.i)Missing header, #error, macro mistakes
Compilecc1 (via gcc -S).iAssembly (.s)Syntax and type errors, warnings
Assembleas (via gcc -c).sRelocatable object (.o)Rare: bad inline assembly
Linkld (via gcc)All .o files and librariesExecutable (.elf)Undefined reference, multiple definition, region overflow

You can stop after any stage to inspect the result:

arm-none-eabi-gcc -E main.c -o main.i      # after the preprocessor
arm-none-eabi-gcc -S main.c -o main.s      # after the compiler: readable assembly
arm-none-eabi-gcc -c main.c -o main.o      # an object file
arm-none-eabi-gcc main.o uart.o -T link.ld -o fw.elf
arm-none-eabi-objcopy -O binary fw.elf fw.bin   # raw image for the flasher

Preprocessing

The preprocessor pastes headers in, expands macros and drops inactive #if branches. The result is one long C file with no # directives left, called a translation unit. Everything the compiler knows about other files comes from declarations in that text.

gcc -E is the fastest way to debug a macro: look at what it actually became.

Compiling

The compiler turns one translation unit into assembly for the target CPU. It sees only that unit. If main.c calls uart_write, the compiler needs a declaration (from uart.h) to check the call, but it has no idea where the function's code is; it leaves a reference to the symbol uart_write for later.

Optimisation happens here. -O0 maps source to instructions almost line by line (easy to debug, large and slow). -Os optimises for size, the usual choice for flash-limited parts. -O2 optimises for speed. -flto delays optimisation until link time so the compiler can inline across files.

Assembling

The assembler turns assembly into machine code inside an object file. An object file contains:

  • sections of code and data (.text, .data, .rodata, .bss), each starting at address 0 because the final addresses are not known yet
  • a symbol table: names this file defines (main, uart_init) and names it uses but does not define (uart_write)
  • relocations: "at offset 0x24 of .text, patch in the address of uart_write"

Linking

The linker reads every object file and library and:

  1. Resolves symbols. Each undefined reference is matched with exactly one definition. None found is undefined reference to 'uart_write'; two found is multiple definition of 'buffer'.
  2. Lays out memory. Following the linker script, it places all .text sections in flash, .data and .bss in RAM, and assigns every symbol its final address.
  3. Applies relocations. Now that addresses are known, it patches every reference.
  4. Discards unused sections if --gc-sections is given and code was compiled with -ffunction-sections.

Libraries (.a files) are archives of object files. The linker pulls in only the objects that define a symbol something still needs, and it scans libraries in command-line order, which is why library order sometimes matters.

#include <stdio.h>

/* In a real project these two would be in separate files. The declaration is what the
   compiler needs; the definition is what the linker needs. */
int scale(int raw);              /* declaration: "this exists somewhere" */

int main(void) {
  printf("scaled = %d\n", scale(21));
  return 0;
}

int scale(int raw) {             /* definition: the code the linker resolves the call to */
  return raw * 2;
}

Pitfall: A function used without any declaration compiles with only a warning in older C standards (implicit int return). If the real function returns float or takes different arguments, the call is silently wrong. Build with -Wall -Werror=implicit-function-declaration.

Errors and the stage they come from

  • fatal error: stm32f4xx.h: No such file or directory: preprocessor. Fix the include path (-I).
  • error: 'GPIOA' undeclared: compiler. A header or definition is missing.
  • undefined reference to 'HAL_Delay': linker. The .c file defining it is not in the build, or a library is missing.
  • region 'FLASH' overflowed by 1024 bytes: linker. The program does not fit; check the map file.

Interview question: Walk through what happens between writing main.c and having a binary on the chip.

Answer: The preprocessor expands includes and macros into a translation unit; the compiler turns that into assembly for the target, optimising as asked; the assembler produces a relocatable object with sections, a symbol table and relocations; the linker combines all objects and libraries, resolves every symbol, places sections at the addresses the linker script gives for flash and RAM, and patches the relocations to produce an ELF. objcopy then extracts a raw .bin or .hex, which a programmer writes to flash through SWD, JTAG or a bootloader.

Interview question: What is the difference between a declaration and a definition, and why does it matter for linking?

Answer: A declaration tells the compiler a name and its type (extern int count; or a function prototype), so code can use it. A definition creates the object or function, and there must be exactly one across the program. Declarations go in headers, definitions in one .c file. Defining a variable in a header that several files include gives multiple definition errors (or, with old -fcommon behaviour, silently merges them).

Going deeper

Interview question: Your smart-watch firmware no longer fits in flash. How do you find room?

Answer: Read the map file sorted by size to see what is big, then check for accidental pulls (printf with floating point, C++ exceptions or RTTI, unused library code), compile with -Os and link-time optimisation, remove dead code with function sections and --gc-sections, move large constant tables to external flash, and compress assets. Measure each change rather than guessing.

Interview question: What does link-time optimisation (LTO) do, and what can go wrong with it in firmware?

Answer: With -flto the compiler stores its intermediate representation in object files and does optimisation across the whole program at link time, allowing inlining and dead-code removal across files, often shrinking firmware noticeably. Problems arise with code the optimiser cannot see being used: interrupt handlers referenced only from the vector table, functions called from assembly or placed in special sections, which need the used attribute, KEEP in the linker script, or __attribute__((externally_visible)).

Interview question: Why does the order of libraries on the linker command line sometimes matter?

Answer: A traditional linker scans libraries once, in order, pulling in only the object files that resolve symbols that are undefined at that point. If library A needs a symbol from library B but B was listed before A, the symbol remains undefined. Listing libraries after the objects that use them, repeating a library, or wrapping a group with --start-group and --end-group fixes it.

Explain it: In your own words, explain why a missing header causes a compiler error but a missing source file causes a linker error.

Answer: The header contains declarations, which the compiler needs while translating a file to check calls and types, so a missing header stops compilation of that file. The source file contains the definitions, the actual code and storage, which the compiler does not need to compile other files, because it just leaves a reference to the symbol. Only when the linker combines all object files does it discover that no object defines that symbol, so it reports an undefined reference.