In C++, putting a function or a variable in an anonymous namespace makes its linkage internal, i. e. the same as declaring it static
on a file-level, but idiomatic C++.
What about an anonymous namespace within a normal namespace? Does it still guarantee internal linkage?
// foo.cpp
void func1() {
// external linkage
}
static void func2() {
// internal linkage
}
namespace {
void func3() {
// internal linkage
}
}
namespace ns1 {
void func4() {
// external linkage
}
namespace {
void func3() {
// still internal linkage?
}
}
}
It's not necessarily the case that entities in an anonymous namespace have internal linkage; they may actually have external linkage.
Since the unnamed namespace has a name that is unique to the translation unit in which it was compiled, you just can't refer to the entities declared in it from outside of that translation unit, regardless of what their linkage is.
The C++ standard says (C++03 7.3.1.1/note 82):
C++11 (draft N3337) §3.5/4: (emphasis mine)
This guarentees that any unnamed namespace has internal linkage.
Although within a named (normal) namespace, it's an unnamed (anonymous) namespace and thus is guaranteed to have internal linkage as per the C++11 standard.
In C++11 the usage of
static
in this context was undeprecated; although unnamed namespace is a superior alternative tostatic
, there're instances where it fails which is remedied bystatic
;inline namespace
was introduced in C++11 to address this.So, I doubt if any of the names 'func3' and 'func4' in your program have internal linkage at all. They have external linkage. However, it is just that they can not be referred from other translation units in accordance with the quote from James.