Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

anonymous namespaces and the one definition rule

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.

like image 821
Lambdageek Avatar asked Oct 31 '11 14:10

Lambdageek


2 Answers

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.

like image 161
Mark B Avatar answered Oct 04 '22 03:10

Mark B


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.

like image 40
Mike Seymour Avatar answered Oct 04 '22 02:10

Mike Seymour