multiple definition and namespace
Asked Answered
I

3

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
Idell answered 28/1, 2011 at 11:16 Comment(0)
G
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.,

Gnash answered 28/1, 2011 at 11:23 Comment(0)
A
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.

Amidst answered 28/1, 2011 at 13:22 Comment(0)
I
0

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

Irrelievable answered 28/1, 2011 at 11:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.