Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does const imply internal linkage in C++, when it doesn't in C?

Tags:

c++

See subject. What were they thinking?

UPDATE: Changed from "static" to "internal linkage" to save confusion.

To give an example... Putting the following in a file:

const int var_a = 1; int var_b = 1; 

...and compiling with g++ -c test.cpp only exports var_b.

like image 619
Johan Kotlinski Avatar asked Jun 15 '09 21:06

Johan Kotlinski


People also ask

What is the point of const in C?

The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed ( Which depends upon where const variables are stored, we may change the value of const variable by using pointer ).

What is internal linkage in C?

Internal Linkage: An identifier implementing internal linkage is not accessible outside the translation unit it is declared in. Any identifier within the unit can access an identifier having internal linkage. It is implemented by the keyword static .

Does const work in C?

Yes. const is there in C, from C89.

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


1 Answers

I believe you mean

Why does const imply internal linkage in C++

It's true that if you declare a const object at namespace scope, then it has internal linkage.

Appendix C (C++11, C.1.2) gives the rationale

Change: A name of file scope that is explicitly declared const, and not explicitly declared extern, has internal linkage, while in C it would have external linkage

Rationale: Because const objects can be used as compile-time values in C++, this feature urges programmers to provide explicit initializer values for each const. This feature allows the user to put const objects in header files that are included in many compilation units.

like image 114
Johannes Schaub - litb Avatar answered Sep 20 '22 08:09

Johannes Schaub - litb