Lesson 172 +10 XP

Unnamed and Inline Namespaces

Unnamed and Inline Namespaces

Two special namespace tricks help you control visibility and keep versions tidy: the unnamed namespace and the inline namespace.

Unnamed namespace: private by default

A namespace without a name gives everything inside it internal linkage - visible only within the current file:

namespace {
    int helper = 5;                // file-private
    void internalThing() { /* ... */ }
}

Code inside the same file can use helper directly (no :: needed). Other files can't see it at all. This is the modern replacement for static.

A namespace that changes the global name

Members of an unnamed namespace act as if they were declared in the enclosing (here, global) scope, but with internal linkage. Two files can each define their own helper without colliding:

// file1.cpp
namespace { int id = 1; }

// file2.cpp
namespace { int id = 2; }   // no conflict, separate variables

Inline namespace: the default version

An inline namespace (C++11) makes its members act as if they belonged to the enclosing namespace. It's often used for versioning:

namespace my {
    inline namespace v1 {
        int version = 1;
    }
    namespace v2 {           // NOT inline
        int version = 2;
    }
}

my::version resolves to the inline v1 version (1). To get the old one explicitly you write my::v2::version (2). When a new version ships, you make v2 inline instead, and existing code keeps working - the inline namespace is the "current default".

TL;DR

  • An unnamed namespace gives internal linkage: visible only in its file.
  • Its members are used without a namespace prefix.
  • It's the modern replacement for static globals.
  • An inline namespace makes its members behave as part of the enclosing namespace.
  • Inline namespaces are great for versioning: the inline one is the current default.