5

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

3 Answers 3

9

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

0
2

Anonymous namespaces make all identifiers they wrap unique to the translation unit they are in. Putting an anonymous namespace into a header that will (sooner or later) be included in different translation units will result in all the identifiers defined in that anonymous namespace to be separately (but identically) in each translation unit.

I have yet to see a use case where one wants this.

0

Yes. Because it give you an ability to name the same things with same names and keep this names simple

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.