Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 foos. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
336 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...