Do internal namespace variables have an internal relationship? If not, then why does the code below work?

This question is directly related to this . Consider the code:

#include <iostream> inline namespace N1 { int x = 42; } int x = 10; int main() { extern int x; std::cout << x; // displays 10 } 

10 displayed. If I remove the extern int x; declaration extern int x; then we get an ambiguity compiler time error

error: reference to 'x' is ambiguous

Question: why does the code work with the extern int x declaration and why does it stop working when I delete it? Is this because inline space variables have an internal relationship?

+8
c ++ c ++ 11 linkage
source share
2 answers

Not. There is no provision in [basic.link] that will cause x to have an internal link. In particular, “All other namespaces have an external connection”, and “other” refers to “not named”. Did you think of unnamed namespaces?

+2
source share

No, the code works because, in order not to violate the existing C code, extern int x; should work just like in C, in other words, creating a local extern for the global namespace (that's all we had in C). Then, when you use it later, a locally declared extern removes any possible ambiguity.

+1
source share

All Articles