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.