|
const in header files
To use const instead of
#define, you must be able to place const
definitions inside header files
as you can with #define. This way, you can place
the definition for a const in a single place and distribute it to
translation units by including the header file. A const in C++ defaults
to internal linkage; that
is, it is visible only within the file where it is defined and cannot be seen at
link time by other translation units. You must always assign a value to a
const when you define it, except when you make an explicit
declaration using
extern:
extern const int bufsize;
Normally, the C++
compiler avoids creating storage for a const, but instead holds the
definition in its symbol table. When you use extern with const,
however, you force storage to be allocated (this is also true for certain
other cases, such as taking the address of a const). Storage must be
allocated because extern says “use external linkage,” which
means that several translation units must be able to refer to the item, which
requires it to have storage.
In the ordinary case, when extern
is not part of the definition, no storage is allocated.
When the const is used, it is simply folded in at compile
time.
The goal of never allocating storage for
a const also fails with complicated structures. Whenever the compiler
must allocate storage, constant folding is prevented (since there’s no way
for the compiler to know for sure what the value of that storage is – if
it could know that, it wouldn’t need to allocate the
storage).
Because the compiler cannot always avoid
allocating storage for a const, const definitions must
default to internal linkage, that is, linkage only within that particular
translation unit. Otherwise, linker errors would occur with complicated
consts because they cause storage to be allocated in multiple cpp
files. The linker would then see the same definition in multiple object files,
and complain. Because a const defaults to internal linkage, the linker
doesn’t try to link those definitions across translation units, and there
are no collisions. With built-in types, which are used in the majority of cases
involving constant expressions, the compiler can always perform constant
folding.
|
|