From Source Code to Running Program
The four stages a C program goes through — preprocess, compile, assemble, link — what each produces, and how to watch them happen.
Typing gcc hello.c hides four distinct stages. Knowing them turns cryptic build errors into obvious ones.
The pipeline
hello.c ──preprocess──▶ hello.i ──compile──▶ hello.s ──assemble──▶ hello.o ──link──▶ a.out
source expanded assembly object executableYou can stop at any stage with gcc:
gcc -E hello.c -o hello.i # 1. preprocess only
gcc -S hello.i -o hello.s # 2. compile to assembly
gcc -c hello.s -o hello.o # 3. assemble to an object file
gcc hello.o -o hello # 4. link into an executable1. Preprocessing
The preprocessor is pure text manipulation: it pastes in #include files, expands #define macros, and strips comments. Open hello.i and you'll see hundreds of lines — the entire contents of stdio.h dropped in above your code.
2. Compiling
The compiler turns your (now self-contained) C into assembly for your CPU — and this is where most of your mistakes surface: type errors, undeclared variables, syntax problems. A compile error means your code didn't make sense to the compiler.
3. Assembling
The assembler converts human-readable assembly into machine code, producing an object file (.o). It's real binary now, but not yet runnable: references to functions in other files (like printf) are still unresolved placeholders.
4. Linking
The linker stitches object files together and resolves those placeholders against libraries (like the C standard library). This is where linker errors live:
undefined reference to 'foo'→ you calledfoobut never provided its definition (forgot a source file or a-llibrary).multiple definition of 'bar'→ the same symbol was defined in two places.
Inspecting the results
nm hello.o # list symbols: T = defined, U = undefined (to be resolved)
file hello # confirm it's an executable for your architecture
ldd hello # which shared libraries it needs at runtimeRun nm on an object file and you'll literally see U printf — undefined until the linker connects it to libc.
Headers vs libraries
A common beginner trap: the header (#include <math.h>) tells the compiler a function exists; the library (-lm) provides its actual code at link time. Include but forget to link and you get a compile-clean, link-failed build.
Takeaways
- Source → preprocess → compile → assemble → link → executable; stop at any stage with
-E/-S/-c. - Compile errors are per-file syntax/type problems; linker errors are missing/duplicate symbols.
nm,fileandlddlet you inspect objects, executables and their library needs.- Headers declare, libraries define — you usually need both.