//file.h
namespace Foo{
namespace{
void func(){}
}
}
vs
namespace Foo{
void func(){}
}
//file2.cpp use file.h's method
What is the consequence (if there is one) in the calling code (in term of visiblity for example) between this two approach ?
This:
namespace Foo {
namespace {
void func() {}
}
}
Is largely equivalent to this:
namespace Foo {
static void func() {}
}
The difference is that in the static
case, the function has internal linkage, so it is not visible to the linker. In the unnamed namespace case, the function has external linkage (is visible to the linker), but under a name which none of your other source files can "normally" access. You might still call the function from a different source file if you reverse-engineer the compiler's name mangling scheme, and the function is still listed among the object file's symbols, for example.
But the common point is that each source file which includes the code (perhaps by #include
ing the header file) will contain its own copy of the function. This can have an impact on the size of your binary.
Also, if you need the first one for some reason, you should heavily document it. An unnamed namespace in a header file is generally a "WTF" point, and you do not want these in your code. I must say I can't think of a viable use case for this.
Both variants will allow the function to be found under the name Foo::func()
.
The compiler might generate different code in the two cases though. Declaring a function inside an anonymous namespace makes that function local to the .cpp
file. That is, every .cpp
file that includes the header might end up with their own (identical) instantiation of the code for func
. This might lead to some bloat in the final executable, due to the duplicated code.
Note that if you define the function inline (as is suggested by your question) this is not really an issue, as the code will be duplicated anyway due to inlining.
Still, as pointed out in the comments: Anonymous namespaces in headers are unusual and will draw the suspicion of however reviews this code. You should always prefer the second option, unless you have very good reason not to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With