Why does const imply internal linkage in C++, when it doesn't in C?
Solution 1:
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.
Solution 2:
As litb said, const
objects have internal linkage in C++. This is because they are intended to be used like this:
// a.cpp
const int BUFSIZE = 100;
char abuf[BUFSIZE];
// b.cpp
const int BUFSIZE = 256
int bbuf[BUFSIZE];
Solution 3:
Const and static are orthogonal concepts in both C and C++.
The const
keyword tells the compiler to disallow the variable from appearing as the lvalue of any expression - essentially making it read-only.
In C, the static
keyword has several uses depending on what it is applied to. When applied to a variable of a function, it indicates that the variable is not stored in the local scope of a function, but is accessible across invocations of it. When applied to a global variable or function, it becomes accessible only to a particular file - in other words, it is accessible only within the compilation unit (unless declared extern
).
In C++, the static
keyword can be used within a class definition, to make a variable or functions shared across all instances of the class, rather than being local to each instance. Furthermore, a static class function in C++ can only access static variables of that class (or classes it has access to). Now, in C++ const
does give members internal linkage to the compilation unit unless they are explicitly declared extern
- this may be what you are referring it. This allows compile-time constants to be shared across unit through the use of header files. Keep in mind, though, that the members are not really static - rather the constant is compiled into each location where it is referenced.