Uses of unnamed namespace in C++

C++Namespaces

C++ Problem Overview


When would one use unnamed namespace in C++ ? Is it better in any sense than a free standing function? Also, should it be used only in source file and not in header file?

C++ Solutions


Solution 1 - C++

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 - C++

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 - C++

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 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAshaView Question on Stackoverflow
Solution 1 - C++T.E.D.View Answer on Stackoverflow
Solution 2 - C++sharptoothView Answer on Stackoverflow
Solution 3 - C++Jeff FosterView Answer on Stackoverflow
Solution 4 - C++fbafelipeView Answer on Stackoverflow