Unnamed namespace Vs Global declaration

c++, declaration, global, namespaces, unnamed-namespace

Solution

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.

Problem

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?

Original source