What if we have to declare only a global constant(not static
)? How extern
help in doing this?
A const
object declared with extern
qualifier has external linkage.
So if you want to use a const
across multiple Translation units, add an extern
qualifier to it.
While a global variable has external linkage by default,why a const global has internal linkage by default?
Reference:
C++03 Standard Annex C Compatibility C.1.2 Clause 3: basic concepts
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.
Avoid the confusion by following a simple rule:
By default Linkage is external for non-const symbols and static (internal) for const symbols.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…