Question

Should the inline keyword be used for variables in anonymous namespaces in a .cpp file?

If I have a constexpr defined in an anonymous namespace in a .cpp file. Should it be declared as inline? Or not?

What would be the difference between the two declarations?

// In my.cpp 
namespace { 
constexpr int kVal{4};
// or
inline constexpr int kOtherVal{4};
} // anonymous namespace

// Later a class or function in my.cpp uses the constant

 3  119  3
1 Jan 1970

Solution

 4

Marking an entity as inline can serve 2 purposes:

  1. Hint for the compiler for optimization (but it may ignore it anyway) - for functions.
  2. Declaring multiple definitions between translation units not to be an ODR violation.

But since all names in an unnamed namespace (including variable names) have internal linkage, this is not really relevant in this case (only one translation unit has access to the name).

Therefore it does not really make a difference here.

2024-07-16
wohlstad