From C++ Source File to Running Process: The Build Pipeline
System DesignModel answerLast updated
Walk a C++ file through preprocessing, compilation, assembly and linking, then explain object files, linker errors and the process address space at launch.
Question
You write a C++ program in main.cpp and run a build command. A runnable binary appears. Describe how the toolchain gets from one to the other.
Part 1: The four stages
For each stage, explain what it does, what it takes as input, and what it produces:
- Preprocessing
- Compilation
- Assembly
- Linking
Part 2: A two-file scenario
The project has two files:
math_utils.cppdefinesint add(int a, int b).main.cppdeclaresaddand calls it.
Answer the following:
- How does an object file (
.o) differ from a finished executable? - Both files compile cleanly, but the link step fails with
undefined reference to 'add'. What is the most likely cause, and what else could produce the same error? - When the OS launches the resulting binary, what happens to the new process's virtual memory?
You are expected to give a structured spoken-style answer. No code needs to be written, but showing the commands you would use to inspect each artifact is a plus.
Hints
Hint 1
For each stage, say what goes in, what comes out, and which names or addresses are still unknown afterwards. Only the last stage sees every file at once.
Hint 2
A compiler needs only a declaration to accept a call. The definition is looked up later, by name, in a different tool. Consider what that name looks like after C++ name mangling.
Hint 3
At launch the kernel maps segments of the file into memory rather than copying the whole file. Think about permissions per segment, the zero-filled region, the stack, the heap, the dynamic loader, and when pages are actually read from disk.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The build is a chain of tools, and each one hands the next a more concrete artifact. The first three stages run independently for every .cpp file. Only the linker sees the whole program.
| Stage | GCC tool | Input | Output | Flag to stop here |
|---|---|---|---|---|
| Preprocessing | cpp | main.cpp | expanded source (main.ii) | -E |
| Compilation | cc1plus | main.ii | assembly (main.s) | -S |
| Assembly | as | main.s | relocatable object (main.o) | -c |
| Linking | ld, driven by g++ | all .o files, libraries, startup files | executable | none |
Part 1: The four stages
Preprocessing is pure text substitution. It pastes in #include files, expands macros, resolves conditional blocks such as #ifdef and include guards, and removes comments. The result is one self-contained translation unit, often tens of thousands of lines once standard headers are included. The preprocessor does not understand C++ syntax or types.
Compilation parses the translation unit, builds an AST, and performs semantic analysis: type checking, overload resolution and template instantiation. It then lowers the code to an intermediate form, optimizes it (-O2), and emits target-specific assembly. It also mangles names, so int add(int,int) becomes something like _Z3addii. Syntax and type errors appear here. When main.cpp calls add, the compiler only needs the declaration. It emits a call to _Z3addii and assumes a definition will exist elsewhere.
Assembly turns mnemonics into machine code and writes a relocatable object file (ELF on Linux). That file contains:
- sections:
.text(code),.data(initialized globals),.rodata(constants) and.bss(zero-initialized globals, which occupy no space on disk); - a symbol table, where
mainis defined and_Z3addiiis marked undefined; - relocation entries, which say things like "patch these four bytes with the final address of
_Z3addii".
The call instruction holds a placeholder for now.
Linking combines everything into one program:
- It gathers the
.ofiles, the startup objects that provide_start, and libraries such as libc and libstdc++. - Symbol resolution matches each undefined symbol to exactly one definition. Zero matches gives an "undefined reference" error, and several strong matches give "multiple definition".
- It merges sections of the same kind and assigns final virtual addresses.
- Relocation patches every placeholder with the real address or offset.
- It writes the executable with an entry point and a program header table.
Part 2: Object file versus executable
| Object file | Executable | |
|---|---|---|
| Scope | one translation unit | whole program |
| Addresses | section-relative, starting at 0 | final virtual addresses (or base-relative for PIE) |
| External symbols | unresolved, with relocation records | resolved, or deferred to the dynamic loader |
| Entry point | none | _start |
| Loadable by the OS | no | yes, it has program headers |
In short, an object file is an incomplete piece with a to-do list (the relocations). An executable is a finished image the kernel knows how to load.
"undefined reference to add"
Compilation succeeded, which means the declaration was fine. The linker simply found no definition under the mangled name _Z3addii. In order of likelihood:
math_utils.onever reached the linker. For example,g++ main.cpp -o appomitsmath_utils.cpp. A missing source in a Makefile or CMake target does the same thing.- The declaration and definition differ, so the mangled names differ. Causes include a different parameter or return type, a definition inside a
namespacethat the declaration is not in, orextern "C"on only one side. - The definition has internal linkage. It is marked
staticor sits in an anonymous namespace, so it is not exported. - Static library order. The linker scans archives left to right, so a library listed before the object that needs it is skipped.
To diagnose, run nm -C main.o math_utils.o. You want to see U add(int, int) in one file and T add(int, int) in the other. If the names or signatures don't match, you have found the problem.
Part 3: Virtual memory at launch
- The shell calls
execve. The kernel discards the old address space and reads the ELF header and program headers. - Each loadable segment is memory-mapped from the file with the right permissions: code as read+execute, constants as read-only, and data as read+write (private, copy-on-write).
.bssis mapped as zero-filled anonymous memory.- If the binary is dynamically linked, the kernel also maps the dynamic loader. The loader maps shared libraries, applies their relocations, fills the GOT, and typically sets up lazy binding through the PLT.
- The kernel builds the stack holding
argc,argv, the environment and the auxiliary vector. The heap begins after.bssand grows viabrk, while large allocations usemmap. - ASLR randomizes the stack, heap, library bases and, for PIE binaries, the executable's own base.
- Demand paging means almost nothing is read up front. A page is loaded on its first access, and read-only pages (such as code) are shared between processes running the same binary.
- Control starts at
_start, goes to__libc_start_main, which runs global constructors, and then reachesmain. Whenmainreturns, destructors andatexithandlers run.
Commands to inspect each artifact
g++ -E main.cpp -o main.ii
g++ -S main.ii -o main.s
g++ -c main.s -o main.o
g++ -c math_utils.cpp -o math_utils.o
nm -C main.o # U add(int, int)
objdump -dr main.o # call plus its relocation entry
g++ main.o math_utils.o -o app
readelf -l app # program headers
Common mistakes
- Confusing compile and link errors. A missing declaration fails at compile time, while a missing definition fails at link time.
- Putting a non-inline function definition in a header that two
.cppfiles include. This causes a "multiple definition" error and violates the One Definition Rule. - Defining a template only in a
.cppfile. Other translation units cannot instantiate it, so the link fails. - Saying the compiler produces the executable. The compiler driver orchestrates several separate programs, and the linker produces the final binary.
- Believing the whole binary is copied into RAM at start. It is mapped and paged in lazily.