Reputation: 1603
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
Upvotes: 5
Views: 3631
Reputation: 224079
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.
Upvotes: 2
Reputation: 145279
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.,
Upvotes: 9
Reputation: 24846
Yes. Because it give you an ability to name the same things with same names and keep this names simple
Upvotes: 0