Static Class Variables and Functions

The Inline Keyword for Static Variables

Why is the inline keyword necessary for static variables in header files?

Abstract art representing computer programming

The inline keyword is necessary for static variables in header files to comply with the One Definition Rule (ODR) in C++. This rule states that any variable or function must be defined exactly once in the entire program to avoid linking errors.

When you define a static variable within a class in a header file, and that header file is included in multiple translation units (i.e., different .cpp files), the compiler will see multiple definitions of the static variable.

This can lead to ODR violations and linking errors. Consider the following example:

// Vampire.h
#pragma once
#include <string>

class Vampire {
public:
  static std::string Faction; 
};
// Vampire.cpp
#include "Vampire.h"

std::string Vampire::Faction{"Undead"};

If Vampire.h is included in multiple .cpp files, each inclusion leads to a new definition of Faction, violating the ODR.

The inline keyword helps to solve this problem by allowing the same definition to be included in multiple translation units without causing linking errors.

When you use inline, the compiler is instructed to treat the variable definition in the header file as if it were defined in each translation unit that includes the header file.

This ensures that the variable is only defined once, avoiding ODR violations:

// Vampire.h
#pragma once
#include <string>

class Vampire {
public:
  static inline std::string Faction{"Undead"}; 
};

The inline keyword tells the compiler that this definition is not an ODR violation. Instead, it is intended to be included in multiple translation units.

Benefits of Using inline

  • Consistency: Ensures that the static variable is consistently defined across all translation units.
  • Convenience: Allows defining and initializing static variables directly in the header file.
  • ODR Compliance: Prevents multiple definition errors during linking.

In summary, the inline keyword is necessary for static variables in header files to comply with the One Definition Rule and to allow safe inclusion in multiple translation units without causing linking errors.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved