Uses of unnamed namespace in C++

Solution 1:

According to Stroustrup, you should use it in places where in old C you would have made static globals. The idea is that the items in question can be "global" to the source file they are in, but not pollute the namespace of any other source files in your compilation.

In other words, you shouldn't be creating static globals in C++. You should be using unnamed namespaces instead.

I have found some situations where they are useful in header files, but that should be rare. Mostly I think for declaring throwable exceptions. In that case the definitions in question will be global for everything that #includes that header, but not for things that don't.

Solution 2:

Unnamed namespace is private to the translation unit and this can be used to shield global variables and functions with same names occurring in different translation units so that no link conflicts arise.

For example, you need a class that will only be defined in a .cpp file and used only within that file. You want to call it CModuleLock. If it is not in an unnamed namespace and some other .cpp file accidentially has another class CModuleLock not in an unnamed namespace you won't be able to link your program.

Solution 3:

It's used for name hiding. Each unnamed namespace is unique. The link here explains in more detail. It is typically used in a source file to hide functions that should only have internal linkage (e.g. not exposed to the outside world).

Solution 4:

Unnamed namespaces are the "C++ version" of global static variables and functions. Note that you can also use a unnamed namespace for classes.