Inline Variables (C++17)
In a Nutshell
Use inline to qualify namespace-scope variables, allowing global variable definitions in headers without producing multiple-definition link errors -- the compiler guarantees a single instance across the entire program.
Header
None (language feature)
Core API Quick Reference
| Syntax | Description |
|---|---|
inline T var = val; | Inline variable definition at namespace scope |
inline constexpr T var = val; | constexpr variables are implicitly inline; no need to repeat the qualifier |
inline static T var = val; | Static member variable inside a class; can be initialized inline since C++17 |
inline thread_local T var = val; | Combined with thread-local storage |
Minimal Example
cpp
// Standard: C++17
// header.h
#pragma once
#include <string>
inline const std::string kVersion = "1.0.0";
inline int kMaxRetries = 3;
// Multiple translation units include this header;
// the linker guarantees only one instance of kVersion and kMaxRetriescpp
// main.cpp
#include <iostream>
#include "header.h"
int main() {
std::cout << kVersion << "\n"; // 1.0.0
std::cout << kMaxRetries << "\n"; // 3
}Embedded Applicability: High
- Ideal companion for header-only libraries, replacing the extern global variable pattern
constexprvariables are implicitlyinline, so compile-time constant tables commonly used in embedded code benefit naturally- Eliminates the boilerplate of "declare in header + define in source file"
- Zero runtime overhead; only affects symbol merging at link time
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 7 | 3.9 | 19.1 |
See Also
Some content adapted from cppreference.com under CC-BY-SA 4.0 license