Anonymous namespace - chunhualiao/public-docs GitHub Wiki
Great question! Anonymous namespaces are a C++ mechanism for giving internal linkage to symbols (functions, variables, classes, etc.) within a translation unit (i.e., a single .cpp file). They are a modern alternative to the old C static keyword for file-local entities.
✅ When to use anonymous namespaces
You should use an anonymous namespace when you want to restrict visibility of names to the current source file:
-
File-local helper functions
- If a function is only meant to be used inside a
.cppfile (not part of the public API), put it in an anonymous namespace.
namespace { void helperFunction() { // only usable in this translation unit } } - If a function is only meant to be used inside a
-
File-local constants or global variables
- Prevents accidental linkage conflicts with other
.cppfiles that might define the same name.
namespace { const int kBufferSize = 1024; } - Prevents accidental linkage conflicts with other
-
File-local types (structs, classes, enums)
- Useful for private helper types that shouldn’t be exposed outside the implementation file.
namespace { struct LocalHelper { int id; }; } -
Avoiding global symbol pollution
- By putting private implementation details in an anonymous namespace, you ensure they won’t clash with symbols from other files during linking.
⚠️ When not to use anonymous namespaces
- In header files → every
.cppfile that includes the header would get its own unique copy of the symbols, leading to ODR (One Definition Rule) violations or code bloat. - For public API → anything meant to be accessed outside the file should go in a named namespace or global scope.
- For inline functions/constants in headers → prefer
inlineorconstexprinstead, since anonymous namespaces in headers cause duplication.
✨ Key points
- Equivalent to
staticfor functions/variables but more powerful (applies to types too). - Ensures internal linkage (symbols are unique to that translation unit).
- Great for encapsulation and avoiding name collisions.
👉 Rule of thumb:
- Use anonymous namespace in
.cppfiles for any helper code that is not part of the module’s external interface. - Avoid them in
.hfiles.
Do you want me to also show you a comparison example: one .cpp file using anonymous namespace vs. another using static to highlight the difference?