Superiority of unnamed namespaces over static

Unnamed namespaces are supposed to be a superior alternative to the static keyword.

I do not understand what an unnamed namespace gives you that cannot just as easily be achieved using the static keyword.

One example, which I found at http://stackoverflow.com/questions/4422507/superiority-of-unnamed-namespace-over-static, is this:

1
2
3
4
namespace 
{  
    class sample_class { /* class body */ };
}


This cannot be achieved by using the static keyword.

While it is certainly true that the static keyword cannot be used in this case, I fail to see what you achieve by putting sample_class in an unnamed namespace. If you write a class definition in a .cpp file, there is (I believe) no way to access it from another .cpp file, regardless of whether it is placed in an unnamed namespace or not.

So what benefit does the unnamed namespace actually give?

--
Claus
If a definition is not inside an unnamed namespace the linker will try to link it to other symbols with the same name even if those are in other source files
... or more generally, static applies to instances whereas types and instances can be placed in namespaces.
I do not see the linker trying to link the names of classes the way you describe.

Consider these two pieces of code:

File 1:
1
2
3
4
5
6
7
8
9
class Alpha {
  public:
    int i;
};

int main() 
{
    Alpha a;
}


File 2:
1
2
3
4
5
6
7
8
void Alpha() 
{
}

void xx() 
{
    Alpha();
}


Although the symbol "Alpha" is defined in both files, I have no problem compiling and linking these files together. (I've tried both with GNU's and Microsoft's compiler.)

Yes, if Alpha is a function or a variable in both files, the linker will complain, but that problem can be solved with "static". So I still want to know: What does an unnamed namespace give me?

Can anybody show me a piece of code that will not work without unnamed namespaces and which cannot be solved equally well using "static"?
1
2
3
4
5
6
7
8
// file 1
namespace S
{
    void foo()
    {
        // something
    }
}

1
2
3
4
5
6
7
8
9
10
// file 2
class S
{
    void foo();
};

void S::foo()
{
    // something else
}

Result:
/tmp/ccvDdNNj.o: In function `S::foo()':
/home/bazzy/file2.cpp:7: multiple definition of `S::foo()'
/tmp/ccrSkKSi.o:/home/bazzy/file1.cpp:4: first defined here
collect2: ld returned 1 exit statu


BTW in C++ the use of static for this purpose has been deprecated
Last edited on
Thank you for that, Bazzy. That was helpful!

According to http://stackoverflow.com/questions/4726570/deprecation-of-the-static-keyword-no-more, the use of static for this purpose is no longer deprecated in C++0x.
Topic archived. No new replies allowed.