正常
inline variables (C++17)
In a Nutshell
Apply inline to a namespace-scope variable, and you can define a global variable in a header file without triggering multiple-definition linker errors—the compiler guarantees exactly one instance across the entire program.
Header
None (language feature)
Core API Cheat Sheet
| 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 specifier |
inline static T var = val; | In-class static data members; since C++17 they can be initialized directly inside the class |
inline thread_local T var = val; | Combines with thread-local storage |
Minimal Example
C++
// 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 a single instance of kVersion and kMaxRetriesC++
// main.cpp
#include <iostream>
#include "header.h"
int main() {
std::cout << kVersion << "\n"; // 1.0.0
std::cout << kMaxRetries << "\n"; // 3
}Embedded Applicability: High
- An ideal companion for header-only libraries, replacing the
externglobal variable pattern. constexprvariables are implicitlyinline, so the compile-time constant tables common in embedded code benefit naturally.- Eliminates the boilerplate of "declare in a header + define in a source file".
- Zero runtime overhead; it only affects symbol merging during linking.
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 7 | 3.9 | 19.1 |
See Also
Part of the content is referenced from cppreference.com, licensed under CC-BY-SA 4.0