Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

linkage

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?

like image 742
vsoftco Avatar asked Nov 23 '15 18:11

vsoftco


People also ask

What are inline namespaces?

Inline namespaces are a library versioning feature akin to symbol versioning, but implemented purely at the C++11 level (ie. cross-platform) instead of being a feature of a specific binary executable format (ie. platform-specific).

What is the meaning of internal linkage?

Internal linkage refers to everything only in scope of a translation unit. External linkage refers to things that exist beyond a particular translation unit. In other words, accessible through the whole program, which is the combination of all translation units (or object files).

What is internal linkage in C++?

internal linkage. A free function is a function that is defined at global or namespace scope. Non-const global variables and free functions by default have external linkage; they're visible from any translation unit in the program. No other global object can have that name.

Which keyword is used for internal linkage?

To use internal linkage we have to use which keyword? Explanation: static keyword is used for internal linkage.


2 Answers

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?

like image 193
Kerrek SB Avatar answered Sep 21 '22 08:09

Kerrek SB


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.

like image 45
Mark B Avatar answered Sep 22 '22 08:09

Mark B