skip to content

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%

answer

  1. same tokens, same meaning
  2. ill-formed, no diagnostic required
  3. the linker keeps one inline copy
  4. a -D flag that changes a layout
  5. results differ with optimisation level

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.

solid answer

~50 s

Classes, inline functions, inline variables and templates may be defined in many translation units, on one condition: every definition is the **same sequence of tokens**, and the names in it mean the same entities. Break that and the program is ill-formed, but outside named modules **no diagnostic is required**, and in practice the build succeeds. The linker never compares class layouts, so `struct Sample` compiled with an extra member in `lib.cpp` and without it in `main.cpp` links; `lib.cpp` then writes past the object `main.cpp` allocated. Inline functions are emitted as mergeable copies and the linker keeps one, so two different `inline int version()` bodies give results that depend on link order and on whether a call was inlined. Typical causes: per-file `-D` flags, stale objects or prebuilt libraries built against an older header, and two libraries defining the same global name.

code

console · 6 lines
console
$ clang++ -std=c++17 -O0 a.cpp b.cpp -o p && ./p
1 1
$ clang++ -std=c++17 -O0 b.cpp a.cpp -o p && ./p
2 2
$ clang++ -std=c++17 -O2 a.cpp b.cpp -o p && ./p
1 2

go deeper

for a junior

Know that a class or inline function in a header must be identical everywhere it is compiled, and that a mismatch may build without errors.

for a middle

Explain why the compiler and linker cannot see these violations: one translation unit at a time, no symbol for a class, one kept copy of an inline function.

for a senior

Diagnose the symptom: corruption that moves with link order, optimisation level or a rebuild. Trace it to per-file macros, stale libraries or colliding global names, and confirm with sanitizers.

for a principal

Make violations structurally unlikely: one build configuration per header, namespaces per component, rebuilt dependencies instead of stale binaries, and sanitizer or LTO checks in CI.

## What the rule demands The one-definition rule has two halves. A **non-inline** function or variable is defined once in the whole program. A **class**, an **inline** function or variable, and a **template** may instead be defined in every translation unit that needs it, which is why they live in headers. For that second group the standard requires that all definitions: - consist of **the same sequence of tokens**, and - mean the same thing: corresponding names denote the same entities, the same overloads and constructors are chosen, constant expressions have the same values. If they do not, the program is **ill-formed**, and the standard requires a diagnostic only when the entity is attached to a named module and an earlier definition is reachable. For ordinary header-based code, that means no diagnostic is required. Nothing in the language obliges the compiler or linker to notice, and they usually do not. ## Why the toolchain stays silent The compiler sees one translation unit at a time; it cannot compare its `struct Sample` with another file's. The linker sees symbols, not types: - A **class's layout** is never recorded as a symbol. It is baked into the code of every function that touches it, so two layouts can coexist in one executable unnoticed. - An **inline function** is emitted by typical toolchains, where it is not inlined, as a mergeable definition in every object file that needs it, and the linker keeps one and discards the rest without comparing their bodies. ## Two failures reproduced **A layout that depends on a macro.** A shared header declares: ```cpp struct Sample { #ifdef WITH_TIMESTAMP long long stamp; #endif int value; }; void fill(Sample& s); ``` `lib.cpp`, built with `-DWITH_TIMESTAMP`, defines `fill` to set `s.stamp = 99` and `s.value = 42`. `main.cpp`, built without it, creates a 4-byte `Sample`, calls `fill` and prints `s.value`. This has **undefined behaviour**: `fill` writes 12 bytes into a 4-byte object. In one plain build on Apple clang 21 it printed `99`, not `42`. Rebuilt with AddressSanitizer, the same program stopped with `stack-buffer-overflow` and `WRITE of size 8`, pointing at `fill(Sample&) lib.cpp:4`. **Two inline functions with one name.** `a.cpp` defines `inline int version() { return 1; }`, `b.cpp` defines it returning `2`, and `main` prints `from_a()` and `version()`. On this machine: | Build | Output | |---|---| | `-O0`, a.cpp linked first | `1 1` | | `-O0`, b.cpp linked first | `2 2` | | `-O2`, either order | `1 2` | At `-O0` every call goes to the single copy the linker kept, chosen by link order; at `-O2` each file inlined its own body. None of these outputs is defined by the standard; they are one toolchain's behaviour. ## Where violations come from 1. **Per-file macros**: a `-DDEBUG`, `-DWITH_TIMESTAMP` or `#pragma pack` that changes a class in some translation units and not others. 2. **Stale binaries**: an object file or a prebuilt static library compiled against an older version of a header, linked with code built against the new one. 3. **Name collisions**: two libraries that each define a global `struct Config` or an inline helper `log_line()` in the global namespace. 4. **Hidden dependence on file-local names**: an inline function in a header that calls a `static` function or uses an unnamed-namespace constant, and so means something different in each file. ## Prevention and diagnosis - **One configuration per header.** Macros that change layouts or inline bodies must be identical for every translation unit and every library in the link, ideally set once for the whole build. - **Namespaces for library types**, unnamed namespaces for file-local ones, so names cannot collide across components. - **Rebuild from source** whenever a header that a binary depends on changes; treat a prebuilt library as tied to the exact headers it was built with. - **Tooling:** GCC's `-Wodr`, enabled by default, warns about ODR violations it can see during link-time optimisation; AddressSanitizer turns layout mismatches into reported out-of-bounds accesses instead of silent corruption. - **Find the surviving copy.** Listing the symbols of each object file shows which ones carry their own copy of an inline function, and stepping into the call in a debugger shows which copy actually runs. - **Read the symptom right.** A crash that moves with link order, optimisation level or an unrelated rebuild, in code that looks correct, is a classic ODR signature.

  • How can a prebuilt static library cause an ODR violation without any source change on your side?
    If the library was compiled against an older version of a header whose class layout or inline functions have since changed, its object code embeds the old layout while your code uses the new one. Both link, because the linker never compares class definitions. Rebuilding the library against the current headers, or pinning the headers to the library's version, removes the mismatch.
  • Do C++20 named modules change this?
    Partly. The standard requires a diagnostic for a conflicting definition when the entity is attached to a named module and an earlier definition is reachable, and module interfaces are compiled once rather than re-pasted per file. Code that still shares classes through headers keeps the old rule: ill-formed, no diagnostic required.

  • The linker reports any class defined differently in two files.
  • If it links, the definitions in the headers must be consistent.
  • Two inline functions with one name both survive, each in its own file.
  • Different -D flags per file are harmless if each file compiles cleanly.
  • An ODR violation always crashes, so it is easy to spot.