Namespaces#

Summary based on C++ Primer, 5th ed. Section 18.2 (Namespaces) and Modern C++ (C++17) best practices.

1. Purpose and Basic Syntax#

Namespaces partition the global scope into distinct logical scopes to prevent name collisions (Global Namespace Pollution) when combining multiple libraries in large-scale programs.

  • No Trailing Semicolon: Unlike class definitions (class Foo { ... };), a namespace block does not end with a semicolon (;).
  • Discontiguous Definitions: A namespace can be split across multiple files (.h and .cc) or blocks. Reopening an existing namespace adds declarations to it rather than creating a new one.
  • Scope Operator (::): Members are accessed via ns::name. Writing a leading ::name with no prefix explicitly refers to name in the global namespace.
  • Nested Namespaces: Namespaces can be nested inside one another; since C++17, nested namespaces can be written concisely as namespace a::b::c { ... }.
int version = 1; // Global namespace (::version)

// Classic nested declaration (pre-C++17)
namespace my_lib {
namespace internal {
  int version = 2;
}
} // No semicolon needed

// C++17 nested namespace shorthand (equivalent)
namespace my_lib::net {

class Client {
public:
  int GetGlobalVersion() const {
    return ::version; // Explicitly accesses global ::version (1)
  }
};

} // namespace my_lib::net

2. Unnamed (Anonymous) Namespaces and Internal Linkage#

A block declared as namespace { ... } without a name is an unnamed (anonymous) namespace.

  • Internal Linkage: Every variable, function, class, or type alias declared inside an anonymous namespace has internal linkage, visible only within the current .cc translation unit and invisible to the linker from any other file. Internally, the compiler treats namespace { ... } as defining a uniquely named hidden namespace followed immediately by using namespace <unique_name>;, so within the same translation unit its members are accessed directly outside the braces without hiding or qualification.
  • Comparison with File-Scope static: File-scope static inherited from C (static int x;, static void f();) also gives internal linkage, but static can only be applied to variables and functions, never to class, struct, or using declarations. An anonymous namespace hides everything inside it uniformly, making it the standard idiom in C++ implementation files.
FeatureFile-Scope staticAnonymous Namespace (namespace { ... })
Applicable EntitiesVariables and free functions onlyVariables, functions, class / struct, enum, using aliases
LinkageInternal LinkageInternal Linkage (C++11+)
C++ RecommendationLegacy compatibilityPreferred standard for file-private code in .cc files

Warning: Never Put an Anonymous Namespace in a Header File (.h)#

Because #include "foo.h" textually copies the header into every .cc translation unit that includes it, placing namespace { ... } in a header gives each translation unit its own distinct private copy, causing three serious bugs:

  1. Code & Data Bloat: Including the header in 100 .cc files duplicates every table and helper function 100 times in the final binary.
  2. Split State Bugs: A mutable or static variable inside namespace { ... } in a header has separate storage in a.cc and b.cc, silently breaking shared state assumptions.
  3. One Definition Rule (ODR) Violation (Undefined Behavior): Any inline function or class template in that header that references an entity from the anonymous namespace binds to a different entity in every .cc file, violating C++’s One Definition Rule (ODR).

Sharing Constants Safely in Headers: Use inline constexpr (C++17+) inside a named namespace so every translation unit shares one single entity.

// config.h (Recommended: C++17 inline constexpr)
namespace app {
inline constexpr int kMaxRetries = 3;
inline constexpr std::string_view kDefaultHost = "localhost";
} // namespace app

3. Namespace Aliases, using Declarations, and using Directives#

C++ provides three mechanisms to avoid repeating long namespace prefixes:

ConstructExampleBehavior & ScopeAllowed in .h Headers?
namespace aliasnamespace fs = std::filesystem;Introduces a short synonym for a long namespace path.Caution (keep inside local/internal scope)
using declarationusing std::string;Brings one specific symbol into the current scope. Collisions are caught immediately at compile time.Only inside function/class scope
using directiveusing namespace std;Makes every name in that namespace visible at once, risking silent overload hijacking or name clashes.Strictly Forbidden

Why using namespace ...; Is Forbidden in Headers: Writing using namespace std; at file scope in a header forces every symbol in std into the global scope of every .cc file that transitively includes that header, causing fragile name collisions across unrelated files.


4. Argument-Dependent Lookup (ADL)#

Ordinarily, functions inside a namespace require explicit qualification (ns::func(x)). However, when an unqualified function call passes arguments of class, struct, or enum type, the compiler automatically searches the namespaces where those argument types are defined. This rule is called Argument-Dependent Lookup (ADL) (or Koenig Lookup).

Two Essential Real-World Uses of ADL#

  1. Operator Overloading (std::cout << s): Writing std::cout << s invokes the non-member operator<<(std::cout, s). Even without writing std::operator<<(std::cout, s), ADL inspects the parameter types (std::ostream and std::string), sees they belong to namespace std, and automatically finds std::operator<<.
  2. The Two-Step swap Idiom in Generic Code (using std::swap; swap(a, b);): Calling std::swap(a, b) with explicit qualification forces the compiler to ignore any specialized swap defined in T’s own namespace. Writing an unqualified swap(a, b) after using std::swap; lets ADL pick T’s custom fast swap if one exists, falling back cleanly to std::swap otherwise:
#include <utility>

namespace custom {
struct Buffer {
  int *data;
};

// Fast custom swap in Buffer's own namespace
void swap(Buffer &lhs, Buffer &rhs) noexcept {
  std::swap(lhs.data, rhs.data);
}
} // namespace custom

template <typename T>
void DoWork(T &a, T &b) {
  using std::swap; // Step 1: Make std::swap available as fallback
  swap(a, b);      // Step 2: Call without std:: qualifier
                   // -> If T is custom::Buffer, ADL selects custom::swap
                   // -> If T is int, falls back to std::swap
}