In the past, I had come by some C++ code that used unnamed namespaces everywhere as the following code shows, and I didn't really know what the meaning of it was:
namespace {

class something {

} // namespace
Until now.

Not using unnamed namespaces in my own code bit me with name clash errors. How? Take ATF. Some of its files declare classes in .cpp files (not headers). I just copy/pasted some ATF code in another project and linked the libraries produced by each project together. Boom! Link error because of duplicate symbols. And the linker is quite right in saying so!

For some reason, I always assumed that classes declared in the .cpp files would be private to the module. But if you just think a little bit about it, just a little, this cannot ever be the case: how could the compiler tell the difference between a class definition in a header file and a class definition in a source file? The compiler sees preprocessed sources, not what the programmer wrote, so all class definitions look the same!

So how do you resolve this problem? Can you have a static class, pretty much like you can have a static variable or function? No, you cannot. Then, how do you declare implementation-specific classes private to a module? Put them in an unnamed namespace as the code above shows and you are all set. Every translation unit has its own unnamed namespace and everything you put in it will not conflict with any other translation unit.

Comments from the original Blogger-hosted post: