Search code examples
c++namespacespragmainclude-guards

multiple definition and namespace


Is that the right way to have functions in namespace that i will #include in multiple files?

test.h

#pragma once
    #ifndef TEST
    #define TEST
    namespace test{
    namespace {

        bool test(){
            return true;
        }
    }
}
#endif //TEST

Solution

  • The include guard name TEST is likely to conflict with some other macro, use something more elaborate, like HEADERNAME_H.

    Note: names that start with underscore followed by uppercase, and names that contain two successive underscores, are reserved for the implementation.

    Secondly, if you're going to put that in a header file, then the function definition needs to be inline. Otherwise, when included in multiple translation units you'll get a multiple definition linker error. Or more formally, the standard's ODR (One Definition Rule) forbids such multiple definitions, unless they're all inline and effectively identical.

    Edit: delete above because I didn't see your use of an anonymous namespace.

    Instead of the anonymous namespace, which gives you a separate namespace in each translation unit and a separate (identical) function definition in each such namespace, instead of that just use inline – as explained in striked-out text above.

    Cheers & hth.,