C++ One Definition Rule – What Means ‘Obey ODR’ in Case of Inline and Constexpr Function

c++c++11constexprinlineone-definition-rule

I just read that constexpr and inline functions obey one-definition rule, but they definition must be identical. So I try it:

inline void foo() {
    return;
}

inline void foo() {
    return;
}

int main() {
    foo();
};

error: redefinition of 'void foo()',
and

constexpr int foo() {
    return 1;
}

constexpr int foo() {
    return 1;
}

int main() {
    constexpr x = foo();
}; 

error: redefinition of 'constexpr int foo()'

So what exactly means that, constexpr and inline function can obey ODR?

Best Answer

I just read that constexpr and inline functions obey one-definition rule, but they definition must be identical.

This is in reference to inline functions in different translations units. In your example they are both in the same translation unit.

This is covered in the draft C++ standard 3.2 One definition rule [basic.def.odr] which says:

There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then

and includes the following bullet:

  • each definition of D shall consist of the same sequence of tokens; and
Related Question