Am I violating the One Definition Rule with the following program?
// foo.hpp
#ifndef FOO_HPP_
#define FOO_HPP_
namespace {
inline int foo() {
return 1;
}
}
inline int bar() {
return foo();
}
#endif
//EOF
and
// m1.cpp
#include "foo.hpp"
int m1() {
return bar();
}
//EOF
and
// m2.cpp
#include "foo.hpp"
int m2() {
return bar();
}
//EOF
and finally
// main.cpp
#include <iostream>
int m1();
int m2();
int main(int, const char* [])
{
int i = m1();
int j = m2();
std::cout << (i+j) << std::endl;
return 0;
}
// EOF
In the above, note that foo()
is defined in an anonymous namespace, so I expect that each translation unit m1.cpp
and m2.cpp
will get its own version, so there is no violation of the ODR. On the other hand, bar()
is just a plain old inline function which happens to call 2 different foo
s. So it violates the ODR, right?
Update:
Previously I had macros in the definition of foo
that changed the value it returned and each of m1
and m2
defined the macro differently before including foo.hpp
. (And with that previous example, g++
would produce a binary that output (i+j)
with a value other than what you would expect.) But in fact this program violates the ODR even if the body of foo()
is identical.
This does violate the ODR. See 3.2/5 which is talking about extern inline functions (bar
):
in each definition of D, corresponding names, looked up according to 3.4, shall refer to an entity defined within the definition of D, or shall refer to the same entity...
In this case bar
refers to two different versions of foo
, thus violating the rule.
Yes, this definition of bar()
does violate the One Definition Rule. You are creating multiple definitions, each of which calls a different function called foo()
.
As you say, it would be a violation even if all versions of foo()
are identical, since they are still different functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With