Skip to content

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.

None (language feature)

Core API Quick Reference

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 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 kMaxRetries
cpp
// 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
  • constexpr variables are implicitly inline, 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

GCCClangMSVC
73.919.1

See Also


Some content adapted from cppreference.com under CC-BY-SA 4.0 license

Built with VitePress