Skip to content

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.

None (language feature)

Core API Cheat Sheet

SyntaxDescription
inline Type var = value;Inline variable definition at namespace scope
const inlineconst 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 inlineUsed 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 extern global variable pattern.
  • const variables are implicitly inline, 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

GCCClangMSVC
73.919.1

See Also


Part of the content referenced from cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05