1

[@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.

thb
  • 13,796
  • 3
  • 40
  • 68
  • 1
    Possible duplicate of [Unnamed/anonymous namespaces vs. static functions](https://stackoverflow.com/questions/154469/unnamed-anonymous-namespaces-vs-static-functions) – thb Mar 15 '19 at 10:54

1 Answers1

3

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.

thb
  • 13,796
  • 3
  • 40
  • 68
  • 1
    How different is this from https://stackoverflow.com/questions/154469/unnamed-anonymous-namespaces-vs-static-functions ? – Passer By Mar 15 '19 at 05:29
  • @PasserBy Aha. Had not found that one. Sorry for the noise. I'll vote to close my own question. – thb Mar 15 '19 at 10:55