* (e-mail address removed):
Please don't top-post in this group. See the FAQ. Corrected.
* (e-mail address removed):
[snip]
I don't really understand the explanation offered by the book.
C++ has a "one definition rule" (often referred to as the "ODR").
In practical terms the ODR is essentially that the linker should only be
presented with /one/ global definition of something -- whatever it is
-- unless that something is
* an 'inline' function, or
* a templated thing,
in which case the linker will simply choose one of the definitions it
encounters, and blithely assume that all others are exactly the same.
The ODR also holds within a translation unit, but (1) that's not a
problem that occurs very often in practice, and (2) within a translation
unit an ODR violation such as
void foo() {} // 1st definition
void foo() {} // 2nd definition, doesn't matter that it's the same
will be detected by the compiler.
Now, when you for example define a not-'inline' function foo in a header
file, and include that header file in more than one translation unit,
then each translation unit will generate one definition of foo, and the
linker will be presented with multiple global definitions of foo, in
violation of the ODR, and most linkers will then complain.
Here I've used the word "global" for definitions that are accessible and
used throughout the program, as opposed to accessible just locally
within a translation unit. The C++ terms are, respectively, "extern
linkage" for global access, and "internal linkage" for access restricted
to the relevant translation unit. 'const' objects that are declared
outside functions and classes have internal linkage by default, so the
ODR does not apply except if you define the same one more than once in
the translation unit's own code. Therefore, you can freely define
'const' objects in header files, as a practical matter. However,
non-'const' objects that are declared outside functions and classes have
external linkage by default, so the ODR does apply. Include that header
file in more than translation unit and the linker will be unhappy.