KatInterview

From C++ Source File to Running Process: The Build Pipeline

System DesignModel answer
EasyModel answerSystem Designc++compilationlinking

Last 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:

  1. Preprocessing
  2. Compilation
  3. Assembly
  4. Linking

Part 2: A two-file scenario

The project has two files:

  • math_utils.cpp defines int add(int a, int b).
  • main.cpp declares add and 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.