cpp17 · advanced
C++17: inline Variables
C++17 inline variables extend the ODR-merging guarantee of inline functions to objects: a variable marked inline may be defined in a header and included in many translation units, and the linker collapses the copies into a single object. This fixes a long-standing pain — before C++17, a non-const static data member had to be declared in the class and defined in exactly one .cpp, so forgetting the out-of-line definition caused a linker error while defining it in the header violated the One Definition Rule, a constant headache for header-only libraries. Now a static data member can be written as static inline int n = 0; directly in the class body, and namespace-scope inline variables provide header-friendly globals. Additionally, constexpr static data members are implicitly inline as of C++17, so they no longer require a separate definition either. Use inline variables for header-only library globals and singletons, configuration constants kept beside their type, and self-defining static members.
C++17 inline variables can be DEFINED in a header and included everywhere (the linker merges them into one), fixing the static-data-member out-of-line definition problem; constexpr static members are implicitly inline since C++17.
The code
// config.h — included by many .cpp filesstruct Config { static inline int max_conns = 64; // C++17: define IN the header};
inline int g_counter = 0; // one shared global, header-only
// pre-C++17: declare in header, DEFINE in exactly one .cpp,// or risk multiple-definition (ODR) link errorsWhat this lesson walks through
- 01The old static-member pain
- 02inline variables fix it
- 03Gotcha — without inline = ODR violation
- 04When to use
Before C++17, a non-const static data member had to be declared in the class (header) and defined in exactly one translation unit (.cpp). Forget the out-of-line definition and you get a linker error; put it in the header and every TU defines it, violating the One Definition Rule. Header-only libraries fought this constantly.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of C++17: inline Variables and 100+ animated C++ interview lessons.