Do inline namespace variables have internal linkage? If not, why does the code below work?

柔情痞子 提交于 2019-12-08 16:53:22

问题


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?


回答1:


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?




回答2:


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.



来源:https://stackoverflow.com/questions/33877510/do-inline-namespace-variables-have-internal-linkage-if-not-why-does-the-code-b

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!