Do inline namespace variables have internal linkag

2019-06-16 09:11发布

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

#include <iostream>

inline namespace N1
{
    int x = 42;
}
int x = 10;

int main()
{
    extern int x;
    std::cout << x; // displays 10
}

It displays 10. If I remove the extern int x; declaration 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 work, and why does it stop working when I remove it? Is it because inline namespace variables have internal linkage?

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-16 09:57

No, the code works because to avoid breaking existing C code, extern int x; has to work the same way in did in C, in other words creating a local extern to a global namespace (that's all we had in C) variable. Then when you use it later the locally declared extern removes any possible ambiguity.

查看更多
3楼-- · 2019-06-16 10:13

No. There is no provision in [basic.link] that would cause x to have internal linkage. Specifically, "All other namespaces have external linkage.", and "other" refers to "not unnamed". Perhaps you were thinking of unnamed namespaces?

查看更多
登录 后发表回答