0

How could I share a constant value that is needed by multiple header files? Or is there some other way around this? What is considered the standard, or is it just preference?

1 Answers1

2

If the variable can be initialized with a constant expression, use

inline constexpr type name = value;

If not, then

inline const type name = value;

The inline keyword allows for the variable to be defined in multiple translation units and not be a violation of the one definition rule

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 1
    Note that this (applying `inline` to variables) requires C++17 or later. Before that it could only be used for functions. – Ben Voigt Jul 14 '20 at 21:55
  • 2
    Good overview of various approaches in different C++ versions: https://stackoverflow.com/a/53896763/103167 – Ben Voigt Jul 14 '20 at 21:58
  • And pre-17 a regular header with regular static constants + constexprs(11) would be the way to go. There are plenty of examples and useful suggestions at https://en.cppreference.com/w/cpp/language/definition – Captain Giraffe Jul 14 '20 at 22:02
  • constexpr implies inline, you can remove the inline – Daniel Jul 14 '20 at 22:19
  • @Dani `constexpr` does not imply inline for variables unless it is a static member variable. – NathanOliver Jul 14 '20 at 22:20