Unnamed namespace Vs Global declaration

4.2k views Asked by At

What is the difference in using unnamed namespace and global declaration?
Is there any specific context for using these two?
Can we access unnamed namespace components in external source files?

2

There are 2 answers

2
Kerrek SB On BEST ANSWER

The point of an unnamed namespace is to provide a unique namespace within a translation unit (= a source file) without requiring an explicit prefix. This allows you to guarantee that your global names won't clash with other, equal global names in other translation units.

For example:

// file1.cpp

namespace
{
    void foo() { /* ... */ }
}

#include "bar.h"

int do_stuff()
{
    foo();
    bar();
    return 5;
}

// file2.cpp

namespace
{
    void foo() { /* ... */ }
}

#include "bar.h"

int do_something else()
{
    bar();
    foo();
    return 12;
}

You can link those two translation units together and know for certain that the two names foo will refer to the function defined in the respective file, and you do not violate the one-definition rule.

Technically, you can think of an unnamed namespace as something like this:

namespace unique_and_unknowable_name
{
    // ...
}

using namespace unique_and_unknowable_name;

Without this tool, the only way you could guarantee a non-violation of ODR would be to use static declarations. However, there's a subtle difference, in that static affects linkage, while namespaces do not.

0
Said Fathelbab On

All names declared inside an unnamed namespace have internal linkage (even names defined with an extern specifier).