Namespaces and Code Organization
Keep names from colliding as your programs grow
audio::play versus video::play.
- explain the name-clash problem and why the linker cannot silently pick a winner,
- define a namespace and access its members with the scope-resolution operator
::, - choose deliberately between a qualified name, a using-declaration, and a using-directive,
- use nested namespaces, namespace aliases, and unnamed namespaces,
- lay out a multi-file program so headers declare and source files define without one-definition-rule violations.
1. The name-clash problem
Every function, class, and global variable you declare introduces a name into some scope. In a tiny program that is harmless. But real projects link together your own code plus third-party libraries, and names are not guaranteed to be unique. Suppose a networking library and a database library both expose a free function called connect:
// net.h
int connect(); // open a network socket
// db.h
int connect(); // open a database session
// main.cpp
#include "net.h"
#include "db.h"
int main() {
return connect(); // ERROR: which connect() is this?
}
The compiler sees two declarations of connect with the same signature. It cannot know which one you meant, and if both were defined the linker would also report a duplicate symbol. This is a name collision. You cannot always rename other people's library functions, so C++ gives you a tool to disambiguate: put each set of names inside its own namespace.