Search code examples
c++namespaces

Uses of unnamed namespace in C++


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?


Solution

  • 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.