Compartilhar via


Unnamed Namespaces

You can declare an unnamed namespace as a superior alternative to the use of global static variable declarations.

namespace { declaration-list }

Remarks

An unnamed namespace definition having the syntax shown above behaves as if it were replaced by:

namespace unique { declaration-list }

using namespace unique;

Each unnamed namespace has an identifier, assigned and maintained by the program and represented here by unique, that differs from all other identifiers in the entire program. For example:

// unnamed_namespaces.cpp
// C2872 expected
namespace { int i; }          // unique::i
void f() { i++; }             // unique::i++

namespace A {
    namespace {
        int i;      // A::unique::i
        int j;      // A::unique::j
    }
}

using namespace A;

void h()
{
    i++;            // C2872: unique::i or A::unique::i
    A::i++;         // A::unique::i++
    j++;            // A::unique::j++
}

Unnamed namespaces are a superior replacement for the static declaration of variables. They allow variables and functions to be visible within an entire translation unit, yet not visible externally. Although entities in an unnamed namespace might have external linkage, they are effectively qualified by a name unique to their translation unit and therefore can never be seen from any other translation unit.

See Also

Reference

Namespaces (C++)