Inline Variables (C++17)
Safe global variables across translation units
The ODR Problem
Before C++17, defining global variables in headers caused One Definition Rule (ODR) violations.
// Old way: header file
// config.h
extern const int max_size; // Declaration in header
// config.cpp
const int max_size = 100; // Definition in one cpp file
// C++17: inline variables - define in header, safe to include everywhere
// config.h
inline constexpr int max_size = 100;
inline const std::string app_name = "MyApp";
// Same instance across all translation units!Use Cases
// Header-only libraries
// math_constants.h
inline constexpr double pi = 3.14159265358979323846;
inline constexpr double e = 2.71828182845904523536;
// Singleton pattern - simpler with inline
// logger.h
class Logger {
public:
static Logger& instance();
void log(const std::string& msg);
};
// Inline variable for the instance
inline Logger& logger = Logger::instance();
// Usage
logger.log("Hello"); // Same logger everywhereComparison
| Approach | Header Safe? | Notes |
|---|---|---|
| const int x = 10; | Internal linkage only | Different in each TU |
| extern const int x; | Requires separate definition | Verbose |
| inline const int x = 10; | ✓ Safe | Same instance everywhere |