Search code examples
c++linkage

Named namespace with internal linkage


[@PasserBy has found that my question is a duplicate. The question can be closed, thanks.]

How can I get a named namespace with internal linkage? That is, how can I get a named namespace invisible to external source files? I want this:

static namespace N {
    int foo() {return 10;}
    int bar() {return 20;}
}

However, unfortunately, C++ does not recognize static namespace.


Solution

  • Enclose the named namespace within an unnamed namespace:

    namespace {
        namespace N {
            int foo() {return 10;}
            int bar() {return 20;}
        }
    }
    
    int sum()
    {
        return N::foo() + N::bar();
    }
    

    This works because an unnamed namespace automatically exports its members (the sole member in this case being the namespace N) to the surrounding scope—without exposing the members to other source files.