Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does const reference have external linkage in C++?

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.

like image 924
spockwang Avatar asked Mar 31 '14 15:03

spockwang


People also ask

Can we use extern with const in C?

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.)

How do you give a const value to an external linkage?

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).

What is external linkage in C?

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.

What does const reference do?

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.


1 Answers

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 or constexpr and neither explicitly declared extern nor previously declared to have external linkage

with no mention of the nonsensical concept of references declared const.

like image 189
Mike Seymour Avatar answered Oct 12 '22 07:10

Mike Seymour