Part ofSystems Programming Companion, week 3
From Source to Binary
You've been writing C, compiling it, watching it run. So what actually happens between typing gcc main.c and seeing a fresh binary appear in the directory? Four distinct stages, and once you've seen each one, you'll never read your own code quite the same way again.
The Four Stages of Compilation
Run gcc main.c -o main and the compiler quietly walks through four transformations:
- Preprocessing - Macro expansion, header inclusion, conditional compilation
- Compilation - C source code to assembly language
- Assembly - Assembly language to machine code (object files)
- Linking - Combining object files into a final executable
Each arrow below is one stage, labelled with the flag that makes GCC stop there and hand you the file it just produced.
You can halt GCC at any stage and read what falls out. It's one of the sharpest tools you have for both debugging and learning.
Stage 1: The Preprocessor
Anything starting with # is the preprocessor's territory. It runs first, before the compiler proper even glances at your file.
// main.c#include <stdio.h>#define MAX_SIZE 100
int main() { int arr[MAX_SIZE]; printf("Array size: %d\n", MAX_SIZE); return 0;}Run just the preprocessor:
gcc -E main.c -o main.iThe resulting main.i is huge — often thousands of lines. #include <stdio.h> doesn't reference the stdio header, it pastes the whole thing in (plus every header that pulls in, recursively). Meanwhile #define MAX_SIZE 100 evaporates entirely; every MAX_SIZE in your code is now the bare literal 100.
// After preprocessing (simplified):// ... thousands of lines from stdio.h ...
int main() { int arr[100]; // MAX_SIZE replaced with 100 printf("Array size: %d\n", 100); // Same here return 0;}The preprocessor is a text substitution engine. It knows nothing about C syntax, types, or semantics. That's why macro bugs feel uncanny — the preprocessor is shoving raw text around before the compiler has any say in the matter.
Stage 2: Compilation (C to Assembly)
This is where the heavy lifting happens. The compiler turns preprocessed C into assembly: human-readable instructions that line up almost one-to-one with what the CPU ends up running.
gcc -S main.c -o main.sSmaller example, cleaner output:
// add.cint add(int a, int b) { return a + b;}Compile to assembly using Intel syntax. We'll stick with Intel throughout this course — to my eye, it just reads more naturally:
gcc -S -masm=intel -O0 add.c -o add.sThe output (add.s) looks something like this:
add: push rbp ; Save the old base pointer mov rbp, rsp ; Set up new stack frame mov DWORD PTR [rbp-4], edi ; Store first argument (a) on stack mov DWORD PTR [rbp-8], esi ; Store second argument (b) on stack mov edx, DWORD PTR [rbp-4] ; Load a into edx mov eax, DWORD PTR [rbp-8] ; Load b into eax add eax, edx ; eax = a + b pop rbp ; Restore old base pointer ret ; Return (result is in eax)Walk through every instruction:
push rbp- Saves the caller's base pointer on the stack. This is part of the standard function prologue.mov rbp, rsp- Sets the base pointer to the current stack pointer, establishing a reference point for this function's stack frame.mov DWORD PTR [rbp-4], edi- The first integer argument arrives in theediregister (System V AMD64 calling convention). This stores it on the stack.mov DWORD PTR [rbp-8], esi- The second argument arrives inesi. Stored on the stack.mov edx, DWORD PTR [rbp-4]- Loadsaback from the stack intoedx.mov eax, DWORD PTR [rbp-8]- Loadsbfrom the stack intoeax.add eax, edx- Addsedx(a) toeax(b). The result lives ineax.pop rbp- Restores the caller's base pointer.ret- Returns to the caller. The return value is ineaxby convention.
At -O0 (no optimisation), the compiler insists on parking every variable on the stack and loading it back before each operation. That's intentional: debuggers want a memory address per variable. Crank it to -O1 or higher and the compiler skips the stack entirely, collapsing the whole function into lea eax, [rdi+rsi]. One instruction.
Stage 3: Assembly (Assembly to Object Code)
The assembler turns text-form assembly into raw machine code:
gcc -c add.c -o add.oThe .o file holds raw machine code, but it can't run on its own yet. objdump will show you what's inside:
objdump -d add.oadd.o: file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <add>: 0: 55 push rbp 1: 48 89 e5 mov rbp,rsp 4: 89 7d fc mov DWORD PTR [rbp-0x4],edi 7: 89 75 f8 mov DWORD PTR [rbp-0x8],esi a: 8b 55 fc mov edx,DWORD PTR [rbp-0x4] d: 8b 45 f8 mov eax,DWORD PTR [rbp-0x8] 10: 01 d0 add eax,edx 12: 5d pop rbp 13: c3 retLeft column: byte offset. Middle column: the actual machine code in hex — those are the literal bytes the CPU eats and executes. 55 is the single-byte encoding of push rbp. mov rbp, rsp takes three bytes: 48 89 e5.
Every address starts at 0. The object file has no idea where it'll be loaded in memory yet — that decision belongs to the linker.
Stage 4: Linking
The linker stitches one or more object files together, resolves symbol references (every call to printf, for instance), and emits the final executable:
gcc add.o main.o -o programA handful of jobs land on the linker's plate:
- Symbol resolution - When
main.ocallsadd(), the linker finds the actual address ofaddinadd.oand patches the call instruction. - Library linking - Functions like
printflive in the C standard library (libc.so). The linker connects your code to these shared libraries. - Address assignment - Each function and global variable gets a final memory address.
- Entry point setup - The linker sets up the
_startroutine that eventually calls yourmain().
Seeing the Final Result
Disassemble the final binary to see the whole thing wired up:
objdump -d program | lessYour add function now has a real address. main's call instructions point at concrete locations. And there's a fair pile of C runtime code that gets the environment in shape before main even gets a turn.
The Optimisation Spectrum
Compare the same function at different optimisation levels:
gcc -S -masm=intel -O0 add.c # No optimisationgcc -S -masm=intel -O2 add.c # Standard optimisationgcc -S -masm=intel -Os add.c # Optimize for sizeAt -O2, our add function becomes:
add: lea eax, [rdi+rsi] ; eax = edi + esi, done in one instruction retThe whole stack frame is gone. No push, no mov to memory, no pop. One lea (load effective address, repurposed here as a fast add) and a ret. Twenty bytes of machine code (offsets 0x0 to 0x13) shrank to four.
Always inspect assembly at the optimisation level you actually ship. Unoptimised assembly hands you a clean, predictable C-to-instruction map. Optimised assembly shows you what the CPU is genuinely going to run on a Tuesday afternoon in production.
Practical Exercise
Try this yourself. Write a simple C file and run each stage:
gcc -E file.c -o file.i # Preprocessgcc -S -masm=intel file.c -o file.s # Compile to assemblygcc -c file.c -o file.o # Assemble to objectgcc file.c -o file # Link to executableobjdump -d file # Disassemble the resultGet comfortable with this loop. The rest of this module leans on compiler output constantly. Reading assembly — even slowly, even painfully at first — is what separates developers who understand their tools from those who merely operate them.