Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 171 ยท Functions

Namespaces

Learn C++ namespaces - defining and reopening them, nested a::b namespaces, aliases, using declarations vs directives, anonymous namespaces, ADL, and the rules for std.

As programs grow, names collide. Your geometry code has a distance function, the networking library you just added has a distance function, and the standard library has std::distance too. In C, the only defense is long prefixes: geo_distance, net_distance. C++ solves this with namespaces: named regions that group related declarations, so that geometry::distance and network::distance can live side by side.

You've used a namespace since your first program: everything in the standard library lives in std, which is why you write std::println. In this lesson you'll create your own namespaces, nest them, give them short aliases, learn the important difference between a using declaration and a using directive (and why using namespace std; is discouraged), use anonymous namespaces to keep helpers private to a file, and see the few rules about adding things to std. The C++ Syntax lesson introduced std::; this lesson gives the full picture.

Defining a namespace

Wrap declarations in namespace name { ... }. Code outside refers to them with the scope resolution operator :::

C++ Two libraries, one function name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The full name of the function is geometry::distance. Inside the namespace, code can use the short name: distance in the body of a geometry function finds geometry::distance first.

A few properties worth knowing:

  • Namespaces are open. You can close a namespace and reopen it later, even in a different file, and add more declarations. That's how a library spreads one namespace across dozens of headers.
  • No semicolon is needed after a namespace's closing brace (unlike a class).
  • Indentation is a style choice. Many codebases don't indent the contents of a namespace, because nearly a whole file would be indented. This lesson indents them for clarity.
  • The global namespace holds everything declared outside any namespace. Refer to it explicitly with a leading ::, as in ::helper().

Nested namespaces and aliases

Namespaces can contain namespaces. C++17 added a compact syntax for declaring them, namespace a::b::c { }, which means the same as three nested blocks. Long nested names are tiresome to type, so you can create a short namespace alias:

C++ Nested namespaces and an alias

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

You'll meet aliases all the time with <chrono> and <filesystem>, whose names are deep: namespace fs = std::filesystem; and namespace chr = std::chrono; are common lines at the top of a .cpp file. Name lookup inside a nested namespace searches outward, so code in shop::billing can say tax::vat instead of the full shop::billing::tax::vat.

using declarations and using directives

There are two ways to bring namespace members into your current scope, and they behave very differently.

A using declaration imports one name:

C++
using std::println;      // now "println" means std::println here
using std::string;

A using directive makes every name in a namespace visible:

C++
using namespace std;     // every std name is now visible without std::

The directive is convenient, and that's its danger. std contains thousands of names, including very common words such as count, distance, size, data, sort, swap, max, find, begin and end. Any of them can collide with your own names, sometimes as a compile error and sometimes, worse, by silently changing which function a call picks:

C++ When using namespace std backfires

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Try changing ::count += 1; to count += 1; and run it: the compiler reports "reference to 'count' is ambiguous", because both ::count and std::count are visible. Worse problems appear when a new C++ version adds a name to std that your code already uses: code that compiled yesterday breaks after a compiler upgrade.

Guidelines that most professional codebases follow:

  • Never put using namespace in a header. It leaks into every file that includes the header, and those files can't undo it.
  • Prefer explicit std::. It's five characters and tells every reader where a name comes from.
  • Use using declarations for a few heavily used names, inside a function or a .cpp file: using std::chrono::milliseconds;.
  • A using directive inside a function for a namespace designed for it is fine, the classic example being literal suffixes: using namespace std::chrono_literals; lets you write 500ms, and using namespace std::string_literals; lets you write "text"s.

A using declaration or directive is scoped like a variable: inside a function body, it only affects that function.

Anonymous namespaces: private to one file

A namespace with no name is an anonymous (unnamed) namespace. Everything inside it has internal linkage: it's visible only in the current source file. Other files can define their own helper with the same name and the linker never sees a conflict:

C++
// report.cpp
namespace {
    // Visible only inside report.cpp.
    std::string pad_left(std::string_view text, std::size_t width) {
        return std::string(width > text.size() ? width - text.size() : 0, ' ') + std::string(text);
    }

    constexpr int max_rows = 50;

    struct RowCache { /* ... */ };
}

void print_report() {
    // pad_left, max_rows and RowCache are usable here, with no prefix.
}

This replaces the C-style use of static on functions and variables (see Scope, Lifetime and Storage Duration) and goes further, because it also works for types. Use an anonymous namespace for every helper in a .cpp file that isn't part of the file's public interface. It prevents accidental clashes, and it lets the compiler optimize more aggressively since it knows no other file can call those functions.

Here's the idea in a single runnable file. The helper's name is short and generic, which is exactly the kind of name that would clash between files if it weren't private:

C++ An anonymous namespace for helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Never put an anonymous namespace in a header: every file that includes it would get its own separate copy of everything inside, which wastes space and breaks anything that should be shared.

How names are found: argument-dependent lookup

You might wonder how std::println("{}", value) and a + b work for types in your namespace when you never qualify the operators. The answer is argument-dependent lookup (ADL): when you call a function by an unqualified name, the compiler also searches the namespaces of the arguments' types:

C++ Argument-dependent lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

describe(bolts) works without inventory:: because bolts is an inventory::Item, so the compiler looks in inventory too. ADL is what makes operators defined next to a type usable everywhere. The lesson: put functions that operate on a type, especially operators, in the same namespace as the type. You'll rely on this in Operator Overloading.

Inline namespaces (versioning)

A namespace declared inline namespace is transparent: its members are also accessible as members of the enclosing namespace. Libraries use it for versioning, so lib::parse can mean lib::v2::parse today while lib::v1::parse remains available for old code:

C++
namespace lib {
    namespace v1 { int parse(const char* text); }
    inline namespace v2 { int parse(const char* text); }   // the default version
}

lib::parse("42");       // calls lib::v2::parse
lib::v1::parse("42");   // the old version, on request

The standard library uses this for literal suffixes: std::literals::chrono_literals is nested in inline namespaces, which is why using namespace std::chrono_literals; and using namespace std::literals; both work.

The std namespace is off limits

Adding your own declarations to namespace std is undefined behavior, even if it seems to work. The standard library reserves the namespace for itself, and a future version could add a name you've used. This is wrong:

C++
namespace std {
    int clamp_percent(int value);   // undefined behavior: you may not add to std
}

There's a narrow exception: you may specialize certain standard templates for your own types when the standard explicitly allows it. The common cases are std::hash<YourType> (so it works as an unordered_map key, see std::unordered_map) and std::formatter<YourType> (so std::println can print it, see Formatting with std::format and std::print). Everything else you write goes in your own namespace.

A good project layout uses one top-level namespace per project or library, named after it (acme::), with nested namespaces for major components (acme::storage, acme::net) and a detail namespace for implementation details that must be in headers but aren't meant for users (acme::detail).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does namespace app::ui { void draw(); } declare?

    Since C++17, namespace a::b { } is shorthand for nested namespace blocks, so draw's full name is app::ui::draw.
  2. 2. Why should you never write using namespace std; in a header file?

    A using directive in a header applies to every file that includes it. Those files suddenly see thousands of names, which can cause ambiguities or silently change overload resolution.
  3. 3. What is the effect of putting a helper function inside namespace { ... } in a .cpp file?

    An anonymous namespace gives its contents internal linkage. Other translation units can't see them and may define their own functions with the same names.
  4. 4. namespace shapes { struct Circle {}; void draw(const Circle&); } In main, shapes::Circle c; draw(c); Does draw(c) compile?

    For unqualified calls, the compiler also searches the namespaces of the argument types. Circle lives in shapes, so shapes::draw is found.
  5. 5. Which of these is allowed?

    Adding declarations to std is undefined behavior. Specializing certain templates, such as std::hash and std::formatter, for your own types is explicitly permitted.

Summary

  • A namespace groups names to prevent collisions; refer to members with ::, and to the global namespace with a leading ::.
  • Namespaces are open and can be reopened anywhere. Nest them with namespace a::b { } (C++17) and shorten long names with an alias (namespace fs = std::filesystem;).
  • A using declaration (using std::println;) imports one name; a using directive (using namespace std;) imports everything and invites collisions. Never use directives in headers.
  • An anonymous namespace makes its contents private to the file (internal linkage); use it for .cpp helpers, never in headers.
  • ADL finds functions and operators in the namespaces of their arguments' types, so keep operations next to their types.
  • Inline namespaces support library versioning.
  • Don't add anything to std, except permitted specializations like std::hash and std::formatter for your own types.

Next: Header Files and Multiple Source Files, where you'll split a program across files and see how the compiler and linker put it back together.