正常
Inline Variables (C++17)
In a Nutshell
Use inline to modify namespace-scope variables, allowing global variable definitions in header files without causing multiple-definition linker errors—the compiler guarantees a single instance across the program.
Header
None (language feature)
Core API Cheat Sheet
| Syntax | Description |
|---|---|
inline Type var = value; | Inline variable definition at namespace scope |
const inline | const variables are implicitly inline, no need to repeat the specifier |
static inline Type var = value; | In-class static member variables; C++17 allows in-class initialization |
thread_local inline | Used with thread-local storage |
Minimal Example
cpp
// config.h
#pragma once
#include <cstdint>
// Define a global configuration in the header
// No need for a separate config.cpp file
inline std::uint32_t system_tick_rate_hz = 1000;
// const variables are implicitly inline
inline constexpr std::size_t buffer_size = 512;
// Class static members can be initialized in-class
class SystemState {
public:
static inline bool is_initialized = false;
};cpp
// main.cpp
#include "config.h"
#include <iostream>
int main() {
// Access the inline variable
std::cout << "Tick Rate: " << system_tick_rate_hz << std::endl;
system_tick_rate_hz = 2000; // Modifies the single shared instance
}Embedded Applicability: High
- An ideal partner for header-only libraries, replacing the
externglobal variable pattern. constvariables are implicitlyinline, so compile-time constant tables commonly used in embedded systems benefit naturally.- Eliminates boilerplate code for "declare in header + define in source file".
- Zero runtime overhead; only affects symbol merging during the linking phase.
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 7 | 3.9 | 19.1 |
See Also
Part of the content referenced from cppreference.com, licensed under CC-BY-SA 4.0