# The one-definition rule

> Every entity gets one definition per translation unit, some get exactly one per program, and classes, inline functions and templates may be defined everywhere as long as every copy is the same. Most violations need no diagnostic, so they show up as wrong behaviour that changes with flags and link order.

- **Source:** C++ Atlas (https://cppatlas.com/topics/one-definition-rule)
- **Track:** Program structure
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [basic.def.odr] (https://eel.is/c++draft/basic.def.odr), [basic.def] (https://eel.is/c++draft/basic.def), [dcl.inline] (https://eel.is/c++draft/dcl.inline), [basic.link] (https://eel.is/c++draft/basic.link), [expr.prim.lambda.capture] (https://eel.is/c++draft/expr.prim.lambda.capture), [temp.expl.spec] (https://eel.is/c++draft/temp.expl.spec)
- **cppreference links:** [Definitions and ODR](https://en.cppreference.com/w/cpp/language/definition), [inline specifier](https://en.cppreference.com/w/cpp/language/inline), [Translation-unit-local entities](https://en.cppreference.com/w/cpp/language/tu_local)
- **Prerequisites:** translation-units-and-linkage

## The one idea

The one-definition rule, the ODR, is the contract that lets separate compilation work. The compiler sees one translation unit at a time and trusts that what it sees there agrees with what every other translation unit sees. The rule has three layers:

1. Within one translation unit, nothing may be defined twice.
2. In the whole program, every non-inline function or variable that is odr-used must be defined exactly once.
3. Classes, enumerations, inline functions, inline variables, templates and a few others may be defined in several translation units, but every definition must be the same, in a strong, token-level sense.

The first layer is checked by the compiler. The second is usually caught by the linker. The third is, for the most part, **ill-formed, no diagnostic required**: the program is broken, nobody is obliged to tell you, and the resulting behaviour is not constrained by the standard.

> **Mental model.** The ODR lets the program behave as if each entity has one definition. Repeating a definition is allowed only where the copies are interchangeable, and the toolchain is free to keep any one of them and throw the rest away.

## One per translation unit, one per program

The per-translation-unit rule is simple and diagnosed. Two definitions of the same class, function or variable in one translation unit are an error, which is what include guards exist to prevent.

The program-wide rule applies to non-inline functions and variables. If such an entity is odr-used, at least one definition must exist somewhere, and if more than one exists in different translation units the program is ill-formed. Neither failure needs a diagnostic, because no single compilation can see it. In practice the linker reports an undefined symbol or a duplicate symbol, but the standard does not promise even that.

```cpp
// helpers.h, included by two .cpp files
int clamp_to_byte(int v) { return v < 0 ? 0 : v > 255 ? 255 : v; }
// two external definitions: ill-formed; usually a duplicate-symbol link error
// fix: mark it inline, or declare it here and define it in one .cpp file
```

A full explicit specialization of a function template is an ordinary function for this purpose. It is not a template, so it is not implicitly inline. Defining `template<> void log<int>(int) { ... }` in a header without `inline` gives one definition per translation unit and the same duplicate-symbol problem.

## Odr-use: when a definition is actually needed

Only odr-used entities need a definition. A function is odr-used when a potentially evaluated expression names it, which covers calls and taking its address. A variable is odr-used when a potentially evaluated expression names it, unless the variable is usable in constant expressions and the expression immediately reads its value, or the expression is a discarded-value expression that does not read it. Binding a reference to the variable, or taking its address, is an odr-use.

The classic casualty is a `static const` data member with an in-class initializer. Reading its value is not an odr-use, but passing it to `std::min`, which takes `const T&`, is.

```cpp
#include <algorithm>

struct Limits { static const int max_items = 64; };  // declaration, not a definition

int clamp_count(int n) {
  int a = Limits::max_items;             // fine: only the value is read
  return std::min(n, Limits::max_items) + a;  // odr-use: binds const int&
}
// without "const int Limits::max_items;" in some .cpp file, GCC and Clang fail to link at -O0;
// at -O2 the call is inlined and it may link anyway
```

Since C++17 the fix is `static constexpr int max_items = 64;`, because a `constexpr` static data member is implicitly an inline variable and its in-class declaration is a definition. The fact that the broken version links at `-O2` is exactly what "no diagnostic required" looks like.

Odr-use also decides what a lambda must capture. A local `const int` initialized with a constant can be read inside a lambda without any capture, because reading it is not an odr-use; taking its address is, and requires a capture.

```cpp
void demo() {
  const int n = 3;
  auto twice = [] { return n * 2; };   // OK: n is not odr-used
  // auto where = [] { return &n; };   // ill-formed: odr-use of n requires a capture
  (void)twice;
}
```

## Many definitions that must be one

For a class, enumeration, inline function, inline variable, templated entity, concept, and a few more, a program may contain one definition per translation unit. [basic.def.odr] then demands that the definitions agree. The main requirements are:

- each definition consists of the **same sequence of tokens**;
- each name in the definitions refers to the **same entity**, after overload resolution, with a narrow exception for constants whose values are read but which are not odr-used;
- overloaded operators, conversions and allocation functions used in the definitions are the same;
- corresponding entities have the same language linkage;
- default arguments used in the definitions satisfy the same requirements;
- for templates, the rules also apply to names looked up at the point of instantiation.

When these hold, the program behaves as if there were one definition. When they do not, and the definitions are not attached to a named module, the program is ill-formed with no diagnostic required.

The same tokens are not enough. Each name must also find the same entity. A `constexpr` variable at namespace scope has internal linkage, so each translation unit has its own copy, and an inline function that odr-uses it refers to a different object in each translation unit.

```cpp
// limits.h, included by several .cpp files
constexpr int max_depth = 32;              // internal linkage: one object per TU

inline int depth_value() { return max_depth; }        // OK: value read, not odr-used
inline const int& depth_ref() { return max_depth; }   // ODR violation: binds a reference
// fix: inline constexpr int max_depth = 32;  (one program-wide object)
```

> **Standardese.** [basic.def.odr] allows a name in the definition to refer to a different object in each translation unit only if the object is a non-volatile `const` object with internal or no linkage, has the same literal type and value in every definition, is initialized with a constant expression, and is not odr-used. `depth_value` satisfies that, and `depth_ref` does not.

Lambda expressions follow the same pattern. A lambda inside an inline function or a template has the same closure type in every translation unit, because the definition containing it is "the same". A lambda that initializes a namespace-scope `constexpr` variable does not: the variable has internal linkage, so each translation unit gets its own variable of its own closure type, and any inline function that calls it refers to different entities in different translation units. Declare such variables `inline constexpr`.

## How violations bite

Because no diagnostic is required, ODR violations rarely fail loudly. These are the common shapes:

- A header defines a struct differently depending on a macro, such as a debug-only member guarded by `#ifndef NDEBUG`, and two libraries are built with different settings. Each side computes different offsets and sizes for the "same" class.
- Two libraries each define a helper with the same name, such as `inline int version()`, or a class called `Node`, with different bodies, in the global namespace.
- A file is compiled with flags that change the meaning of the tokens, such as a different `#pragma pack`, a different `-D` value, or a different language standard that changes a library type's layout.
- A function is declared `inline` in one translation unit and not in another.

The second shape is easy to reproduce. Two translation units define `inline int version()` returning 1 and 2, and each calls it. With GCC 16 at `-O0` both calls return the same value, which one depends on the link order. At `-O2` each call is inlined and returns its own translation unit's value. None of these outcomes is a bug in the compiler.

> **Pitfall.** `static` inline functions and functions in unnamed namespaces are immune, because each translation unit has its own entity. That is also a cost: a `static inline` function in a header gives each translation unit its own copy of any `static` local variable, so a counter or cache in it is silently per-translation-unit.

The rule for inline declarations has its own quiet trap. [dcl.inline] requires that if a function with external linkage is declared `inline` in one translation unit, an inline declaration is reachable in every translation unit that declares it, with no diagnostic required. In practice, an inline function is only emitted where it is odr-used. If the translation unit that sees `inline` never calls it, another translation unit that declared it non-inline gets an undefined-symbol error. If it does call it, the program may link at `-O0` and stop linking at `-O2`, once that call is inlined.

## Vague linkage: how implementations cope

The standard only says "behave as if there is one definition". Implementations deliver that with **vague linkage**. On ELF and Mach-O platforms that use the Itanium C++ ABI, a compiler emits every inline function, inline variable, template instantiation, static local guard variable and `typeinfo` object it needs as a weak or COMDAT symbol. The linker keeps one copy of each and discards the others without comparing them. On macOS, `nm -m` shows such a symbol as `weak external`.

```text
a.o:  weak external  version()   -> returns 1
b.o:  weak external  version()   -> returns 2
          \                         /
           linker keeps the first one it sees;
           calls that were inlined keep their own copy
```

Virtual tables follow a related convention. The Itanium ABI emits a class's vtable in the translation unit that defines its **key function**, the first non-inline, non-pure virtual member function. Without one, the vtable is emitted with vague linkage wherever it is needed.

Some tools can find ODR violations that compilers are not required to diagnose. GCC's link-time optimizer warns about mismatched type definitions with `-flto -Wodr`, enabled by default under LTO, and on Linux AddressSanitizer can report some global variables that are defined twice. Neither compares inline function bodies; in the `version()` example above, GCC 16 with `-flto -Wodr` says nothing.

Since C++20, definitions attached to a named module change the picture: an importer reaches the module's one definition instead of compiling its own copy, and a second definition is diagnosable when an earlier one is reachable. The modules topic covers that in detail.

## What to remember

- One definition per translation unit is diagnosed; one per program for non-inline functions and variables is not, and usually surfaces at link time.
- Only odr-used entities need definitions; binding a reference or taking an address is an odr-use, reading a constant's value is not.
- `static constexpr` data members are inline since C++17 and need no out-of-line definition.
- Repeated definitions of classes, inline entities and templates must have the same tokens and must find the same entities.
- An inline function that odr-uses a namespace-scope `constexpr` variable violates the ODR; use `inline constexpr`.
- Explicit specializations of function templates are not implicitly inline.
- ODR violations are ill-formed, no diagnostic required; results change with optimization level and link order.
- Vague linkage keeps one arbitrary copy of each inline entity; `-flto -Wodr` catches type mismatches, not differing function bodies.

## Concept Map Outline

- **One-definition rule:** The program must behave as if each entity had exactly one definition.
  - **Three layers:** Per translation unit, per program, and repeated definitions that must match.
    - **One per TU:** Two definitions of anything in one translation unit are diagnosed.
    - **One per program:** Non-inline odr-used functions and variables need exactly one definition overall.
    - **Repeatable items:** Classes, enums, inline entities, templates and concepts may be defined once per TU.
  - **Odr-use:** Only odr-used entities need a definition to exist.
    - **Reading a constant:** An immediate read of a variable usable in constant expressions is not an odr-use.
    - **References and addresses:** Binding a reference or taking the address is an odr-use, as with std::min(x, S::n).
    - **Lambda captures:** A lambda may read a local constant uncaptured but must capture it to take its address.
    - **static constexpr:** Since C++17 constexpr static members are inline and need no out-of-class definition.
  - **Same definitions:** Repeated definitions must match token for token and in meaning.
    - **Same tokens:** Each definition must consist of the same sequence of tokens.
    - **Same entities:** Names must find the same entities after overload resolution in every TU.
    - **Constant exception:** Internal-linkage constants may differ per TU only if they are not odr-used.
    - **Lambdas:** Lambdas in inline functions share one closure type; namespace-scope constexpr ones do not.
  - **How it bites:** Violations are ill-formed, no diagnostic required, so nothing has to warn you.
    - **Macros and flags:** NDEBUG, -D values or #pragma pack can make one class two layouts.
    - **Name clashes:** Two libraries' inline version() or Node with different bodies in one namespace.
    - **Varies with -O:** At -O0 the linker's copy wins; at -O2 each TU may inline its own body.
    - **Missing inline:** inline in one TU but not another is ill-formed and may fail to link at -O2.
  - **Vague linkage:** Implementation practice: emit weak or COMDAT copies and keep one.
    - **Weak symbols:** Inline functions, template instantiations and guard variables; nm -m shows weak external.
    - **Key function:** Itanium ABI emits a vtable with the first non-inline, non-pure virtual function.
    - **Detection tools:** GCC -flto -Wodr catches mismatched types but not differing inline function bodies.

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.def.odr])

This header is included by `a.cpp` and `b.cpp`, which are linked into one program. What does the standard say?

```cpp
// util.h
int twice(int x) { return 2 * x; }
```

A. Well-formed: the two definitions are token-for-token identical
B. Ill-formed, and the compiler must issue a diagnostic
C. Well-formed: the linker is required to keep one copy
D. Ill-formed, no diagnostic required; linkers usually report a duplicate symbol

**Answer (D):** Ill-formed, no diagnostic required; linkers usually report a duplicate symbol

**Why:** `twice` is a non-inline function with external linkage, so the program may contain only one definition of it. Two translation units each contain one, which [basic.def.odr] makes ill-formed, and because the definitions are not attached to a named module no diagnostic is required; no single compilation can see both. The identical-tokens answer is tempting, but that permission only applies to inline functions, classes, templates and the other entities [basic.def.odr] lists.

### Question 2 [warmup] ([basic.def.odr], [class.static.data])

There is no definition of `S::n` outside the class. Which function odr-uses `S::n`, so that the program needs such a definition?

```cpp
#include <algorithm>

struct S { static const int n = 5; };

int a()    { return S::n; }
int b()    { return S::n + 1; }
int c(int k) { return std::max(k, S::n); }
int d()    { int arr[S::n]{}; return arr[0]; }
```

A. `a`
B. `b`
C. `c`
D. `d`

**Answer (C):** `c`

**Why:** `S::n` is usable in constant expressions, so an expression that immediately reads its value does not odr-use it; that covers `a`, `b` and the array bound in `d`. `std::max` takes its arguments by `const int&`, and binding a reference to `S::n` is an odr-use, so `c` requires a definition, and GCC and Clang fail to link it at `-O0`. Since C++17, `static constexpr int n = 5;` would be an inline variable and need no extra definition.

### Question 3 [warmup] ([basic.def.odr], [temp.expl.spec])

Which of these may be defined, identically, in several translation units of one program?

A. A non-inline function `int f() { return 1; }`
B. A class `struct Point { int x, y; };`
C. A namespace-scope variable `int counter = 0;`
D. A full explicit specialization `template<> int g<int>() { return 1; }` without `inline`

**Answer (B):** A class `struct Point { int x, y; };`

**Why:** Classes are among the definable items that [basic.def.odr] allows once per translation unit, provided every definition is the same. The explicit specialization is the tempting wrong answer: it lives next to a template, but a full specialization of a function template is an ordinary function and is not implicitly inline, so repeating it is an ODR violation. The non-inline function and the non-inline variable may have only one definition in the program.

### Question 4 [tricky] ([basic.def.odr], [dcl.inline])

`a.cpp` contains `inline int version() { return 1; }` and `b.cpp` contains `inline int version() { return 2; }`. Both call `version()`, and both are linked into one program. What does the standard say?

A. It is unspecified which of the two definitions is used
B. Well-formed: each translation unit uses its own definition
C. The program is ill-formed, no diagnostic required
D. Ill-formed, and the linker must diagnose the mismatch

**Answer (C):** The program is ill-formed, no diagnostic required

**Why:** Inline functions may be defined in several translation units only if every definition consists of the same tokens with the same meaning. These do not, so [basic.def.odr] makes the program ill-formed with no diagnostic required, which places no requirement on its behaviour. "Unspecified" is tempting because it describes what you observe: GCC 16 at `-O0` uses one body for both calls, chosen by link order, and at `-O2` inlines each translation unit's own body. That observation is not a guarantee of anything.

### Question 5 [tricky] ([basic.def.odr], [basic.link])

This header is included by several translation units of one program. What is its status?

```cpp
// limits.h
constexpr int max_depth = 32;

inline const int& depth_ref() { return max_depth; }
```

A. Ill-formed, no diagnostic required: `depth_ref` refers to a different object in each translation unit
B. Well-formed: `max_depth` is constexpr, so every translation unit sees the same value
C. Well-formed, but `depth_ref()` returns a dangling reference
D. Ill-formed: a constexpr variable cannot be returned by reference

**Answer (A):** Ill-formed, no diagnostic required: `depth_ref` refers to a different object in each translation unit

**Why:** A namespace-scope `constexpr` variable is `const` and therefore has internal linkage, so each translation unit has its own `max_depth`. The inline function's definitions are token-identical but name different entities, and the exception for constants only applies when the constant is not odr-used; binding the returned reference odr-uses it. The "same value" answer is right for `return max_depth;` by value, which is why it tempts. Declaring the variable `inline constexpr` fixes it.

### Question 6 [tricky] ([dcl.inline], [basic.def.odr])

The header defines `inline int next() { static int n = 0; return ++n; }`. `a.cpp` includes it and defines `int fa() { return next(); }`. `main.cpp` also includes it. What does this `main.cpp` print?

```cpp
#include <cstdio>

inline int next() { static int n = 0; return ++n; }
int fa();

int main() {
  int x = fa();
  int y = next();
  std::printf("%d %d\n", x, y);
}
```

A. `1 1`, because each translation unit has its own `n`
B. `1 2`
C. Either `1 1` or `1 2`, depending on inlining
D. Undefined behavior, because `n` is defined in two translation units

**Answer (B):** `1 2`

**Why:** An inline function with external linkage is one entity across the program, and a static local variable in it is one object, whichever translation unit's copy runs. So `fa()` returns 1 and the later `next()` returns 2, regardless of optimization. `1 1` is what you would get from `static inline int next()`, which gives each translation unit a separate function and therefore a separate `n`.

### Question 7 [standardese] ([basic.def.odr], [expr.prim.lambda.capture])

Which lambda makes `demo` ill-formed?

```cpp
void demo() {
  const int n = 3;
  auto a = [] { return n; };
  auto b = [] { return n * 2; };
  auto c = [] { return sizeof(n); };
  auto d = [] { return &n; };
}
```

A. `a`, because `n` is not captured
B. `d`
C. `c`, because `sizeof` names `n`
D. None of them; `n` has automatic storage but is a constant

**Answer (B):** `d`

**Why:** A lambda without a capture default may only name a local entity if doing so is not an odr-use. `n` is a `const int` initialized with a constant, so it is usable in constant expressions, and reading its value in `a` and `b` is not an odr-use; `sizeof(n)` is an unevaluated operand. Taking its address in `d` is an odr-use, which requires a capture, so `demo` is ill-formed and GCC and Clang reject it. Option `a` is the tempting answer for anyone who expects every outside variable to need a capture.

### Question 8 [standardese] ([dcl.inline], [basic.def.odr])

`a.cpp` defines `inline int helper() { return 42; }`. `b.cpp` declares `int helper();` without `inline` and calls it. What does the C++23 standard say?

A. Well-formed: `a.cpp` provides the definition the linker needs
B. Well-formed only if `a.cpp` also calls `helper`
C. Ill-formed, and a diagnostic is required at link time
D. Ill-formed, no diagnostic required: an inline declaration must be reachable in every translation unit that declares the function

**Answer (D):** Ill-formed, no diagnostic required: an inline declaration must be reachable in every translation unit that declares the function

**Why:** [dcl.inline] requires that if a function with external linkage is declared inline in one definition domain, an inline declaration of it is reachable from the end of every definition domain that declares it, with no diagnostic required, and `b.cpp` breaks that rule. [basic.def.odr] separately requires an inline function to be defined wherever it is odr-used, which `b.cpp` also fails. The second option describes what happens in practice with GCC at `-O0`, where `a.cpp` emits an out-of-line copy only if it uses the function, but that copy may vanish at `-O2` and the program then fails to link.
