Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

free function inside anonymous namespace

Tags:

c++

//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 ?

like image 348
Guillaume Paris Avatar asked Feb 12 '23 15:02

Guillaume Paris


2 Answers

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 #includeing 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.

like image 165
Angew is no longer proud of SO Avatar answered Feb 15 '23 05:02

Angew is no longer proud of SO


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.

like image 26
ComicSansMS Avatar answered Feb 15 '23 03:02

ComicSansMS