Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 961
Stals Avatar asked Dec 29 '22 02:12

Stals


1 Answers

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

like image 95
Cheers and hth. - Alf Avatar answered Jan 12 '23 14:01

Cheers and hth. - Alf