c++staticc++17inlineinline-variable

Why are non member static constexpr variables not implicitly inline?


In C++17 we got inline variables and I have assumed that global constexpr variables are implicitly inline. But apparently this is true only for static member variables.

What is the logic/technical limitation behind this?

source:

A static member variable (but not a namespace-scope variable) declared constexpr is implicitly an inline variable.


Solution

  • The point here is that constexpr int x = 1; at namespace scope has internal linkage in C++14.

    If you make it implicitly inline without changing the internal linkage part, the change would have no effect, because the internal linkage means that it can't be defined in other translation units anyway. And it harms teachability, because we want things like inline constexpr int x = 1; to get external linkage by default (the whole point of inline, after all, is to permit the same variable to be defined in multiple translation units).

    If you make it implicitly inline with external linkage, then you break existing code:

    // TU1
    constexpr int x = 1;
    
    // TU2
    constexpr int x = 2;
    

    This perfectly valid C++14 would become an ODR violation.