skip to content

Compilation Model

C++ is compiled one translation unit at a time and linked afterwards, which explains headers, the ODR, mangling and modules. Interviewers ask why a link error appears.

on this pageshow

explore

questions

28

In C++, what is the difference between a declaration and a definition, and which of them belongs in a header file?

level: juniorimportance: must knowfreq 74%

answer

  1. names something versus creates it
  2. a body or storage makes it a definition
  3. #include pastes text into each file
  4. class definitions may repeat across files
  5. extern int n; versus int n;

basics

~20 s

A declaration introduces a name and its type; a definition also creates the entity: a function's body, a variable's storage. Headers hold declarations, class definitions and inline or template code; ordinary function and variable definitions go in exactly one .cpp file.

solid answer

~50 s

A **declaration** introduces a name and its type so that code can refer to it: `int area(int w, int h);`, `extern int frame_count;`, `class Lidar;`. A **definition** is a declaration that also creates the thing: the function's body, the variable's storage, the class's full member list. Every definition is also a declaration, but not every declaration is a definition. `#include` pastes a header's text into every source file that names it, so whatever a header holds is compiled once per translation unit. That is why headers carry declarations, class definitions, and inline functions and templates, which the one-definition rule lets several translation units define identically, while a non-inline function body or a global variable's definition goes in exactly one `.cpp` file. Put one of those in a header and every file that includes it defines it again.

code

cpp · 19 lines
cpp
#include <cstdio>

// What a header would hold: declarations only.
extern int tick_count;            // declares a variable, no storage
int add_ticks(int n);             // declares a function, no body
struct Odometry;                  // declares a class, which stays incomplete
struct Velocity { double v; };    // a class definition is shared too

// What exactly one .cpp file would hold: the definitions.
int tick_count = 0;
int add_ticks(int n) {
    tick_count += n;
    return tick_count;
}

int main() {
    add_ticks(3);
    std::printf("%d\n", add_ticks(4));
}

go deeper

for a junior

Recall the one-line rule: a declaration names something, a definition creates it. Give one example of each for a function, a variable and a class, and say which file each one lives in.

for a middle

Explain #include as text pasted into every translation unit, then show why that makes a non-inline function body in a header fail at link time while a class definition there is fine.

for a senior

Show that you keep headers lean on purpose: declarations and class definitions only, bodies and private helpers in the .cpp, so editing an implementation recompiles one file instead of every includer.

for a principal

Treat each header as a published contract: what it exposes sets the rebuild cost and the coupling for every consumer, and that is the lever when a large codebase's build time keeps growing.

## Declarations and definitions in the standard's terms A **declaration** introduces a name into a translation unit and says what kind of thing it is: a function with these parameter and return types, a variable of this type, a class. That is enough for the compiler to check every use of the name. A **definition** is a declaration that also *creates* the entity. The C++ standard states it the other way round: every declaration is a definition **unless** it falls into one of a list of exceptions. The exceptions that matter day to day are: - a function declared **without a body**: `int area(int w, int h);` - a declaration with the `extern` specifier and **no initializer**: `extern int frame_count;` - a **non-inline static data member** declared inside its class: `static int limit;` - an **elaborated type specifier**, the forward declaration `class Lidar;` - a `typedef`, an alias declaration, a `using`-declaration or a `using`-directive So `int frame_count;` at namespace scope is a definition: it creates storage, and because it has static storage duration it is zero-initialized. `extern int frame_count = 0;` is a definition too, because the initializer outweighs the `extern`. ```cpp extern int frame_count; // declaration only int area(int w, int h); // declaration only class Lidar; // declaration only: Lidar is incomplete int frame_count = 0; // definition: storage int area(int w, int h) { // definition: body return w * h; } struct Pose { double x, y; }; // definition of the class Pose ``` ## What #include actually does `#include "pose.h"` is replaced by **the entire text** of `pose.h` before the compiler proper sees the file. The standard calls a source file, plus everything it includes, minus lines skipped by conditional compilation, a **translation unit**. Each `.cpp` file is compiled on its own into an object file, and the **linker** then joins the object files into one program, matching each use of a function or variable to its single definition. Two consequences follow: 1. A header is not compiled by itself. Its text is compiled again inside **every** translation unit that includes it, directly or through another header. 2. A call needs only a **declaration** in the calling file. The compiler emits a reference to the function's symbol, and the linker resolves it against whichever object file holds the definition. ## What goes where | Construct | Header | One `.cpp` file | |---|---|---| | Function declaration | yes | the definition | | Non-inline function body | no | yes | | `extern` variable declaration | yes | the definition | | Class definition | yes, it is shared | member function bodies | | Inline function, function template | yes, identical in every file | — | | File-private helpers | no | yes | The class definition is the interesting row. The one-definition rule says a **non-inline** function or variable is defined once in the whole program, but it allows a class, an inline function, an inline variable or a template to be defined in several translation units, **provided every definition is the same sequence of tokens with the same meaning**. A class must be defined in each translation unit that needs its size or members, so its definition has to live in a header. Within a single translation unit, though, each entity may still be defined at most once, which is the job of include guards. ## Why the split exists Separate compilation is what makes the split pay off. If `planner.cpp` changes, only `planner.cpp` is recompiled and the program relinked. If `planner.h` changes, every file that includes it is recompiled. Keeping bodies in `.cpp` files therefore keeps edits cheap, and keeping only declarations in headers keeps every includer independent of implementation details. ## Common mistakes - **A non-inline function body in a header.** It compiles, then the link fails as soon as two `.cpp` files include the header, because each object file now defines the function. - **A global variable defined in a header** as `int frame_count = 0;`: the same failure. The header should hold `extern int frame_count;` and one `.cpp` file the definition. - **Declaring without ever defining.** A function that is declared, called and defined nowhere compiles fine; the link then typically fails with an undefined symbol. - **Believing `#include` links code.** It copies text; linking is a later, separate step.

  • Is int x; at namespace scope a declaration or a definition?
    A definition: it creates storage, and as a variable with static storage duration it is zero-initialized. Only `extern int x;` with no initializer is a pure declaration, and `extern int x = 0;` becomes a definition again because of the initializer. That is why a header that says `int x;` produces a duplicate definition as soon as two `.cpp` files include it.
  • What does a .cpp file need before a call to a function in another file compiles?
    Only a declaration: the name, the parameter types and the return type, so the compiler can check the call and emit a reference to the function's symbol. The body can live in any other translation unit, and the linker connects the call to it. If no translation unit defines the function, every file still compiles and the link typically fails with an undefined-symbol error.
  • Why can a class definition appear in many translation units when a function body cannot?
    The one-definition rule allows a class, an inline function, an inline variable and a template to be defined in several translation units as long as every definition is token-for-token identical with the same meaning. A non-inline function or variable gets no such allowance and must be defined once in the program. Inside one translation unit, any entity may be defined only once.

  • A header file is compiled into its own object file.
  • Declaration and definition are two words for the same thing.
  • Function bodies belong in headers so the compiler can see them.
  • #include links the other file's compiled code into this one.
  • A forward declaration like class Lidar; defines an empty class.
open as a page

In C++, what problem do include guards solve, and how does #pragma once differ from an #ifndef guard?

level: juniorimportance: must knowfreq 68%

basics

~20 s

They stop one header's text from being compiled twice in the same translation unit, which would redefine its classes. An #ifndef guard is standard and keyed by a macro name; #pragma once is a widely supported, non-standard pragma keyed by the file itself.

open as a page

In C++, why replace #define constants and function-like macros with constexpr variables, inline functions or templates?

level: juniorimportance: must knowfreq 58%

basics

~20 s

Macros are text substitutions done before the compiler parses C++, so they ignore types, scopes and namespaces, can evaluate an argument twice and vanish from debuggers. constexpr variables, inline functions and templates do the same jobs as real, checked entities.

open as a page

In C++, how does using std::cout; differ from using namespace std;, and why does the second not belong in a header?

level: juniorimportance: must knowfreq 72%

basics

~20 s

using std::cout; declares one name in the current scope; using namespace std; makes every std name visible to unqualified lookup. In a header the directive reaches every file that includes it, so names such as count become ambiguous there.

open as a page

In C++, why does a C caller get an undefined symbol for a function compiled as C++, and what does extern "C" change?

level: middleimportance: must knowfreq 62%

basics

~20 s

C++ compilers mangle names, encoding namespace, class and parameter types into the symbol, so a C caller looking for the plain name finds nothing. extern "C" gives the function C language linkage: an unmangled name, and therefore no overloading.

open as a page

A C++ utility function defined in a header causes a multiple-definition link error; why, and which fixes are correct?

level: middleimportance: must knowfreq 72%

basics

~20 s

Each .cpp file that includes the header compiles its own external definition, but a non-inline function may be defined once per program. Mark it inline or move the body into one .cpp file; static also links, but gives each file a private copy.

open as a page

In C++, what is argument-dependent lookup, and why does std::cout << v need it to find an operator<< declared in v's namespace?

level: middleimportance: must knowfreq 62%

basics

~20 s

Argument-dependent lookup adds, for an unqualified function call, the functions declared in the namespaces of the argument types. It lets std::cout << v find geo::operator<< for a geo::Vec2 without a qualifier or a using-declaration at every call site.

open as a page

In C++, why does a derived class that declares scale(int) make the base class's scale(double) overloads uncallable through a derived object?

level: middleimportance: must knowfreq 58%

basics

~20 s

Name lookup stops at the first scope that declares the name, before overload resolution runs. The derived scale(int) hides every base scale, so a double argument is converted to int or the call fails. using Base::scale; restores them.

open as a page

Your C++ plugin SDK ships as a shared library; which changes to its classes break plugins compiled against the previous release, and why?

level: seniorimportance: must knowfreq 55%

basics

~20 s

Changing anything a plugin compiled in from the old header breaks it: sizes and member offsets, virtual functions, base classes, inline bodies and default arguments, plus any changed signature. Adding non-virtual, non-inline functions or new classes is safe; pimpl keeps layout out of headers.

open as a page

In C++, what does extern int frame_count; declare, and where must the matching definition of frame_count live?

level: juniorimportance: should knowfreq 52%

basics

~20 s

It declares a variable with external linkage without defining it, so no storage is created. Exactly one .cpp file must define it, as int frame_count = 0;, and every file that sees the declaration refers to that one variable.

open as a page

In a C++ header, when can you forward-declare a class instead of including its header, and when must you include it?

level: middleimportance: should knowfreq 58%

basics

~20 s

A forward declaration such as class Lidar; makes Lidar an incomplete type: enough for pointers, references and function declarations. Anything needing its size or members, such as a by-value member, a base class, sizeof or a member call, needs the definition.

open as a page

In C++17, what problem do inline variables solve for globals and static data members defined in a header?

level: middleimportance: should knowfreq 50%

basics

~20 s

Before C++17 a header could only declare a shared variable or static data member, and one .cpp file had to define it. An inline variable may be defined in every file that includes the header and is still one object.

open as a page

In C++, what distinguishes external, internal and no linkage, and how do static and an unnamed namespace give internal linkage?

level: middleimportance: should knowfreq 55%

basics

~20 s

Linkage decides whether one name in different scopes or files denotes the same entity. External: shared across translation units. Internal: private to one translation unit. No linkage: most block-scope names. static, or an unnamed namespace, makes a namespace-scope name internal.

open as a page

In a C++ build, why do #if LOGX_TRACE and #ifdef LOGX_TRACE disagree for -DLOGX_TRACE=0 and for a misspelled macro name?

level: middleimportance: should knowfreq 35%

basics

~20 s

#ifdef asks only whether the macro is defined, so -DLOGX_TRACE=0 counts as on. #if evaluates an expression in which every identifier that is not a macro becomes 0, so 0, a missing macro and a misspelled name all silently count as off.

open as a page

Why does std::min(a, b) in a C++ logging header stop compiling when <windows.h> is included before it, and how do you fix it?

level: middleimportance: should knowfreq 45%

basics

~20 s

<windows.h> defines function-like macros named min and max unless NOMINMAX is defined first. The preprocessor expands min( even after std::, so the compiler sees std:: followed by an expression. Define NOMINMAX project-wide, or write (std::min)(a, b).

open as a page

In C++23, after import std; why does code using assert or INT_MAX still need an #include, and what does std.compat add?

level: middleimportance: should knowfreq 35%

basics

~20 s

import std exports declarations only; assert, INT_MAX, errno, EOF and offsetof are macros, so they still need #include <cassert> or <climits>. std.compat additionally exports the C library names in the global namespace, such as ::printf.

open as a page

In C++20, how does a named module's interface unit differ from a header, and what can an importing file actually see?

level: middleimportance: should knowfreq 48%

basics

~20 s

A module interface unit is compiled once into a binary interface; an importer sees only its exported declarations, never its macros or unexported names, and the importer's own macros cannot change how the module was compiled.

open as a page

Why is passing std::string across a C++ plugin boundary risky when plugins may be built with a different compiler or standard library?

level: seniorimportance: should knowfreq 42%

basics

~20 s

The standard fixes std::string's interface, not its layout; libstdc++ and libc++ differ, and libstdc++ itself has two string ABIs. Mismatches fail to link, or worse, link and corrupt memory, so boundaries use C types or pin one toolchain.

open as a page

In a C++ robotics codebase, editing one header triggers a 30-minute rebuild; how do you find why and cut that dependency?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Find every translation unit that reaches the header, directly or transitively, and why. Then cut edges: remove unused includes, forward-declare instead of including, move bodies and private members into .cpp files, split catch-all headers, and use pimpl for classes whose private parts churn.

open as a page

Why can two C++ translation units that define the same struct or inline function differently link cleanly, yet misbehave at run time?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Every definition of a class or inline function must be token-for-token identical with the same meaning, but violations need no diagnostic. Linkers never compare class layouts and keep one inline copy, so mismatches surface as corrupted data or wrong results.

open as a page

Before using std::expected in a C++ header built as both C++17 and C++23, why test __cpp_lib_expected rather than __has_include(<expected>) or __cplusplus?

level: seniorimportance: should knowfreq 38%

basics

~20 s

__has_include only says a header file exists; libc++ ships <expected> in every mode but declares nothing before C++23. __cplusplus names the language mode, not what the library implements. __cpp_lib_expected, from <version> or <expected>, says std::expected is usable.

open as a page

In a C++20 logging library, which jobs of a LOG macro can std::source_location take over, and which still need the preprocessor?

level: seniorimportance: should knowfreq 33%

basics

~20 s

std::source_location::current() as a defaulted parameter captures the caller's file, line and function, replacing FILE and LINE. A macro is still needed to stringize an expression, to skip evaluating message arguments when a level is off, and to compile calls out entirely.

open as a page

When a C++20 module mathlib is split into partitions, what must the primary interface do with them, and how do imports constrain build order?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Every interface partition must be re-exported by the primary interface with export import :name; internal partitions stay private. Partitions are importable only inside their module, and since an importer needs each imported unit's BMI first, imports form an acyclic build order.

open as a page

In C++, what is a hidden friend operator, and why do library authors define operator== and operator<< that way?

level: seniorimportance: should knowfreq 32%

basics

~20 s

A hidden friend is a non-member function defined with friend inside a class body. Ordinary and qualified lookup cannot see it; only argument-dependent lookup finds it when the class is an argument, which keeps overload sets small and diagnostics short.

open as a page

In generic C++ code, why write using std::swap; swap(a, b); instead of std::swap(a, b), and what does C++20's std::ranges::swap change?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A qualified std::swap(a, b) never sees a type's own cheaper swap. The two-step keeps std::swap as a fallback and lets argument-dependent lookup find a swap declared beside the type. C++20's std::ranges::swap does that lookup for you.

open as a page

As lead of a C++ plugin SDK shipped as a shared library to third parties, what ABI-stability policy do you set across releases?

level: principalimportance: should knowfreq 38%

basics

~20 s

Decide what you promise and enforce it: a C-linkage boundary with opaque handles for any toolchain, or a pinned C++ toolchain with pimpl'd classes; hidden-by-default symbols, a load-time ABI version check, CI symbol diffs and breaks only in major releases.

open as a page

Your team's C++ math library has many #include consumers; how do you decide whether and how to also ship it as a C++20 named module?

level: principalimportance: should knowfreq 30%

basics

~20 s

Adopt when every supported compiler and build system handles named modules; then ship a wrapper interface unit over the existing headers, export-using or extern "C++" style, so header and module users coexist and the symbol names stay unchanged.

open as a page

In C++, how does an inline namespace let a library ship a new version of its types while users keep writing geo::Point?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

Members of an inline namespace are used as if declared in the enclosing namespace, so geo::Point names geo::v2::Point. The version stays in mangled names, so code built against v1 and code built against v2 refer to different symbols for functions that use Point.

open as a page