c++ - Why are unnamed namespaces used and what are their benefits?

ID : 10239

viewed : 38

Tags : c++oopnamespacesc++

Top 5 Answer for c++ - Why are unnamed namespaces used and what are their benefits?

vote vote

100

Unnamed namespaces are a utility to make an identifier translation unit local. They behave as if you would choose a unique name per translation unit for a namespace:

namespace unique { /* empty */ } using namespace unique; namespace unique { /* namespace body. stuff in here */ } 

The extra step using the empty body is important, so you can already refer within the namespace body to identifiers like ::name that are defined in that namespace, since the using directive already took place.

This means you can have free functions called (for example) help that can exist in multiple translation units, and they won't clash at link time. The effect is almost identical to using the static keyword used in C which you can put in in the declaration of identifiers. Unnamed namespaces are a superior alternative, being able to even make a type translation unit local.

namespace { int a1; } static int a2; 

Both a's are translation unit local and won't clash at link time. But the difference is that the a1 in the anonymous namespace gets a unique name.

Read the excellent article at comeau-computing Why is an unnamed namespace used instead of static? (Archive.org mirror).

vote vote

81

Having something in an anonymous namespace means it's local to this translation unit (.cpp file and all its includes) this means that if another symbol with the same name is defined elsewhere there will not be a violation of the One Definition Rule (ODR).

This is the same as the C way of having a static global variable or static function but it can be used for class definitions as well (and should be used rather than static in C++).

All anonymous namespaces in the same file are treated as the same namespace and all anonymous namespaces in different files are distinct. An anonymous namespace is the equivalent of:

namespace __unique_compiler_generated_identifer0x42 {     ... } using namespace __unique_compiler_generated_identifer0x42; 
vote vote

71

Unnamed namespace limits access of class,variable,function and objects to the file in which it is defined. Unnamed namespace functionality is similar to static keyword in C/C++.
static keyword limits access of global variable and function to the file in which they are defined.
There is difference between unnamed namespace and static keyword because of which unnamed namespace has advantage over static. static keyword can be used with variable, function and objects but not with user defined class.
For example:

static int x;  // Correct  

But,

static class xyz {/*Body of class*/} //Wrong static structure {/*Body of structure*/} //Wrong 

But same can be possible with unnamed namespace. For example,

 namespace {            class xyz {/*Body of class*/}            static structure {/*Body of structure*/}   } //Correct 
vote vote

66

In addition to the other answers to this question, using an anonymous namespace can also improve performance. As symbols within the namespace do not need any external linkage, the compiler is freer to perform aggressive optimization of the code within the namespace. For example, a function which is called multiple times once in a loop can be inlined without any impact on the code size.

For example, on my system the following code takes around 70% of the run time if the anonymous namespace is used (x86-64 gcc-4.6.3 and -O2; note that the extra code in add_val makes the compiler not want to include it twice).

#include <iostream>  namespace {   double a;   void b(double x)   {     a -= x;   }   void add_val(double x)   {     a += x;     if(x==0.01) b(0);     if(x==0.02) b(0.6);     if(x==0.03) b(-0.1);     if(x==0.04) b(0.4);   } }  int main() {   a = 0;   for(int i=0; i<1000000000; ++i)     {       add_val(i*1e-10);     }   std::cout << a << '\n';   return 0; } 
vote vote

59

The example shows that the people in the project you joined don't understand anonymous namespaces :)

namespace {     const int SIZE_OF_ARRAY_X;     const int SIZE_OF_ARRAY_Y; 

These don't need to be in an anonymous namespace, since const object already have static linkage and therefore can't possibly conflict with identifiers of the same name in another translation unit.

    bool getState(userType*,otherUserType*); } 

And this is actually a pessimisation: getState() has external linkage. It is usually better to prefer static linkage, as that doesn't pollute the symbol table. It is better to write

static bool getState(/*...*/); 

here. I fell into the same trap (there's wording in the standard that suggest that file-statics are somehow deprecated in favour of anonymous namespaces), but working in a large C++ project like KDE, you get lots of people that turn your head the right way around again :)

Top 3 video Explaining c++ - Why are unnamed namespaces used and what are their benefits?

Related QUESTION?