Interview Q&A · C++ · 10 questions in this topic
Compilation, Linking & ODR — C++ Interview Q&A
The build model interviewers love — translation units, headers, include guards, linkage, ODR and static vs dynamic libraries. Part of Compilation, Linking & ODR · 213 questions in the C++ bank.
What is a translation unit?
Answer
A translation unit is one source file after preprocessing (all #includes expanded, macros processed) — the actual input the compiler translates. Each .cpp typically forms one TU; headers are fragments pasted into TUs, never compiled alone.
One-definition and linkage rules operate per-TU and across TUs, which is why the same header included twice needs guards.
Example
// main.cpp includes <vector> + "widget.h" → one TU // widget.cpp includes "widget.h" → another TU // the linker joins their object files
What is the One Definition Rule (ODR)?
Answer
Across the program, each non-inline function, variable, class and enum has exactly one definition (inline variables/functions and templates may repeat identically per TU). Within a TU, no entity may be defined twice. Violations may link silently with merged duplicates (inline) or fail — or worse, exhibit UB from differing definitions.
Headers carry declarations; definitions live in one .cpp unless inline/template.
Example
// widget.h: declaration void paint(); // widget.cpp: single definition void paint() {}
What are include guards and what is `#pragma once`?
Answer
Both prevent double inclusion within one TU: classic guards use #ifndef/#define/#endif around the header; #pragma once is the shorter compiler-supported equivalent. Guards protect against diamond includes and self-inclusion.
#pragma once is universally supported and simpler, but non-standard (still fine in practice); guards are standard and work everywhere including exotic filesystems.
Example
// widget.h #pragma once // ...or standard guards: // #ifndef WIDGET_H // #define WIDGET_H // ... // #endif
What is the difference between static and dynamic linking?
Answer
Static linking copies library code into the executable: single file, no runtime dependency, larger binary, updates require relinking. Dynamic linking references shared libraries loaded at startup: smaller binaries, shared memory, independent updates — at the cost of load time, versioning (DLL hell / SO versioning) and deployment complexity.
Static suits self-contained tools; dynamic suits system libraries and plugin ecosystems.
Key points
- 1Static (.a/.lib) — baked in at link time.
- 2Dynamic (.so/.dll/.dylib) — resolved at load/run time.
- 3Trade-off — size and hermeticity vs sharing and updatability.
What do `extern`, internal linkage and anonymous namespaces do?
Answer
extern declares without defining (for cross-TU variables/functions) and can specify language linkage (extern "C"). File-static and anonymous-namespace entities get internal linkage — private to their TU. Named namespaces with inline variables/functions share across TUs by design.
Modern style prefers anonymous namespaces over file-static for TU-local helpers.
Example
// shared.cpp int shared_counter = 0; // external linkage // user.cpp // extern int shared_counter; // declaration, defined elsewhere namespace { int local_helper() { return 1; } } // TU-local
💡 extern declares, static/anonymous hides, inline shares — the linkage trio in one line.
What is `extern "C"` and why does C++ need it?
Answer
It switches a declaration to C language linkage: no name mangling, so C code (and dlsym, FFI, shared-library ABIs) can find the symbol. C++ mangles overloaded names into unique symbols; C does not — extern "C" bridges that gap.
It does not make the code C — the body is still C++ (overloads inside are banned, exceptions still propagate unless caught).
Example
#ifdef __cplusplus extern "C" { #endif void plugin_init(void); // unmangled, callable from C #ifdef __cplusplus } #endif
What is name mangling?
Answer
Name mangling encodes a C++ entity scope, name, types and qualifiers into a unique linker symbol (e.g. _ZN3foo3barEi), enabling overloads, namespaces and templates to coexist at link time. It is implementation-defined — different compilers mangle differently, which is why cross-compiler static linking fails.
Demangle with c++filt or nm -C when reading linker errors; extern "C" disables mangling for interop.
Example
// g++ mangled vs demangled: // _ZN1S3addEii → S::add(int, int) // inspect: nm -C libfoo.a | grep add
What is the difference between compiler, linker and loader errors?
Answer
Compiler errors are per-TU: syntax, types, undeclared names — with file/line diagnostics. Linker errors are cross-TU: undefined reference (declared, never defined/linked), multiple definition (ODR), missing library paths. Loader errors happen at startup: missing shared libraries, ABI mismatches, bad rpaths.
Read the phase first: the phase tells you where to look (code vs build graph vs deployment).
Key points
- 1Compiler — inside one TU: types and syntax.
- 2Linker — across TUs: symbols and libraries.
- 3Loader — at startup: shared objects and paths.
Example
// undefined reference to `Widget::paint()` → linker: widget.cpp missing // error: no matching function → compiler: overload/type bug
💡 Naming the phase before debugging saves most build-investigation time.
How do you reduce C++ build times?
Answer
Cut work per TU (forward declare, IWYU includes, precompiled headers, lean headers), cut redundant work (ccache, extern templates), and parallelize/distribute (parallel jobs, distcc/icecc, unity builds for cold builds). Modules (C++20) attack the root cause — header re-parsing — where toolchains support them.
Measure first: -ftime-trace / build profilers show whether headers, templates or linking dominate.
Key points
- 1Less input — forward declarations, lean/PCH headers.
- 2Less repeat — ccache, extern templates, unity builds.
- 3More parallelism — jobs, distributed builds, faster linker (lld/mold).
💡 Forward-declare plus measure-with-trace is the credible senior answer, not just buy a faster machine.
What should a header contain vs a source file? (Interface hygiene.)
Answer
Headers: declarations, class definitions, inline/template/constexpr definitions, type aliases, constants. Source files: non-inline function definitions, static data definitions, TU-local helpers in anonymous namespaces.
Self-containment (header compiles alone), minimal includes (forward declare the rest), and no using-namespace at global scope keep builds fast and ODR-clean.
Example
// widget.h: interface + inline/template only #pragma once class Widget { public: void paint(); }; // widget.cpp: the one definition // #include "widget.h" // void Widget::paint() {}
Recommended resourcesAffiliate links · may earn us a commission