C++ Namespaces | Complete Guide to Name Boundaries

C++ Namespaces | Complete Guide to Name Boundaries

이 글의 핵심

How to structure namespaces, use `using` safely, and align directories with `myapp::net`-style APIs.

Why namespaces?

Multiple libraries and teams share one program. Namespaces partition the global scope so Graphics::Point and Math::Point can coexist.

namespace MyLib {
    int value = 10;
    void print() { std::cout << "MyLib\n"; }
}

int main() {
    std::cout << MyLib::value << '\n';
    MyLib::print();
}

using declaration

Brings one name into scope:

using std::cout;
using std::endl;

using directive

Brings all names from a namespace into lookup (risky in large scopes):

using namespace std;

Declaration vs directive

using std::coutusing namespace std
ScopeSingle nameEntire namespace
Collision riskLowerHigher
HeadersSometimes OK (narrow)Avoid

Nested namespaces

namespace Company::Project::Utils {
    void helper();
}

Anonymous namespace

namespace {
    const int kBufferSize = 1024;
    void logInternal(const char* msg) { /* ... */ }
}

Prefer over file-scope static functions in many style guides (C++11+).

Namespace aliases

namespace Http = Project::Networking::Http;

The std namespace

Standard library entities live in std (with documented exceptions). Do not add your own types into std except where the standard permits (e.g. certain trait specializations per rules).

Project layout

include/myapp/net/client.h   // namespace myapp::net
src/net/client.cpp
  • Public API in headers under namespace myapp::net { ... }.
  • Implementation in .cpp with same namespace or out-of-line definitions.
  • File-local helpers in anonymous namespace.

Why not using namespace std in headers?

Headers are included everywhere. A directive pulls in count, min, distance, etc., which can silently clash with user code and change overload sets.


  • ADL
  • Inline namespace

Keywords

C++, namespace, using, std, encapsulation