According to clause 3 of section 3.5 of C++ 1998 standard, a const reference has internal linkage.
A name having namespace scope (3.3.5) has internal linkage if it is the name of
an object, reference, function or function template that is explicitly declared static or,
an object or reference that is explicitly declared const and neither explicitly declared extern nor previously declared to have external linkage; or
a data member of an anonymous union.
But why multiple definition conflict is generated when compiling the following code?
// a.cpp
const int& a = 1;
int main()
{
return 0;
}
// b.cpp
const int& a = 1;
And then compile the code.
$ g++ a.cpp b.cpp
/tmp/ccb5Qi0M.o:(.bss+0x0): multiple definition of `a'
/tmp/ccD9vrzP.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
If the const reference is changed to const, as follows
// a.cpp
const int a = 1;
int main()
{
return 0;
}
// b.cpp
const int a = 1;
It is OK to compile.
The extern must be applied in all files except the one where the variable is defined. In a const variable declaration, it specifies that the variable has external linkage. The extern must be applied to all declarations in all files. (Global const variables have internal linkage by default.)
Although constexpr variables can be given external linkage via the extern keyword, they can not be forward declared, so there is no value in giving them external linkage. This is because the compiler needs to know the value of the constexpr variable (at compile time).
External Linkage: An identifier implementing external linkage is visible to every translation unit. Externally linked identifiers are shared between translation units and are considered to be located at the outermost level of the program.
Const Reference to a pointer is a non-modifiable value that's used same as a const pointer. Here we get a compile-time error as it is a const reference to a pointer thus we are not allowed to reassign it.
The reference itself isn't const
, just the object it refers to; so (arguably) this rule doesn't give the reference internal linkage.
It doesn't make sense for a reference to be declared const
. The C++11 standard clarifies the wording:
a variable that is explicitly declared
const
orconstexpr
and neither explicitly declaredextern
nor previously declared to have external linkage
with no mention of the nonsensical concept of references declared const
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With