Search code examples
c++language-lawyerconstexprc++23one-definition-rule

Are multiple identical non-inline constexpr variable definitions allowed in different translation units in C++23?


C++23 says that constexpr functions and static data members are implicitly inline, but it does not say the same for namespace-scope constexpr variables. It also says that: "For any definable item D with definitions in multiple translation units, if D is a non-inline non-templated function or variable... the program is ill-formed."

Since inline variables were only introduced in C++17, there are a lot of legacy header files with non-inline constexpr variables. Why is it not illegal for multiple translation units to contain definitions of the same constexpr variable, as in:

// include.h
constexpr int my_constant = 1;

Solution

  • Your example does not define the same variable more than once; it defines a separate variable with internal linkage in each TU where include.h is #included ([basic.link]/8).

    [dcl.constexpr]/6:

    A constexpr specifier used in an object declaration declares the object as const.

    [basic.link]/3.2:

    The name of an entity that belongs to a namespace scope has internal linkage if it is the name of

    • a non-template variable of non-volatile const-qualified type