Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

An inline variable is a variable declared with the inline specifier, allowing it to be defined in multiple translation units without violating the One Definition Rule (ODR). Introduced in C++17, it instructs the linker to merge all identical definitions of the variable across different object files into a single, shared instance in memory. Crucially, if an inline variable is odr-used in a translation unit, a definition of that variable must be present in that exact translation unit (typically achieved by placing the definition in a shared header file).

Syntax

// Namespace scope
inline int global_counter = 0;

// Class scope (static data member)
struct Entity {
    inline static int entity_count = 0;
};

Technical Mechanics

  • ODR Exemption and Requirement: Standard variables defined in a header file and included in multiple .cpp files result in a multiple-definition linker error. The inline specifier exempts the variable from this strict ODR enforcement, permitting multiple definitions. However, it mandates that every translation unit that odr-uses the variable must contain its definition.
  • Linker Resolution: When the linker encounters multiple definitions of an inline variable, it selects one definition and discards the others. All translation units referencing the variable will resolve to the exact same memory address.
  • Identical Definitions Requirement: Every definition of the inline variable across all translation units must be token-for-token identical. If the definitions differ, the program is ill-formed, no diagnostic required (IFNDR), which results in undefined behavior.
  • Linkage: Inline variables declared at namespace scope possess external linkage by default. They are visible across translation units unless explicitly marked static (which would force internal linkage, creating distinct, unshared instances per translation unit).
  • Initialization: Dynamic initialization of an inline variable occurs exactly once. The initialization is sequenced before the first statement of main, or deferred until the variable is odr-used, depending on the implementation.

Implicit Inline for constexpr

As of C++17, any constexpr static data member of a class is implicitly declared inline. It does not require a separate out-of-class definition to be odr-used (e.g., when its address is taken or it is bound to a reference).
struct Configuration {
    // Implicitly inline in C++17+
    // No out-of-class definition (constexpr int Configuration::max_connections;) is needed
    static constexpr int max_connections = 50; 
};
Master C++ with Deep Grasping Methodology!Learn More