Skip to content

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.

None (language feature)

Core API Cheat Sheet ​

SyntaxDescription
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 kMaxRetries
C++
// 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 extern global variable pattern.
  • constexpr variables are implicitly inline, 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 ​

GCCClangMSVC
73.919.1

See Also ​


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

pdf-latest-4-g85128cc · 85128cc · 2026-10-05