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:

  1. File-local helper functions

    • If a function is only meant to be used inside a .cpp file (not part of the public API), put it in an anonymous namespace.
    namespace {
        void helperFunction() {
            // only usable in this translation unit
        }
    }
    
  2. File-local constants or global variables

    • Prevents accidental linkage conflicts with other .cpp files that might define the same name.
    namespace {
        const int kBufferSize = 1024;
    }
    
  3. 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;
        };
    }
    
  4. 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 .cpp file 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 inline or constexpr instead, since anonymous namespaces in headers cause duplication.

✨ Key points

  • Equivalent to static for 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 .cpp files for any helper code that is not part of the module’s external interface.
  • Avoid them in .h files.

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?