Why can I include a header file in multiple cpp files containing const int and no compiler error?
Suppose I have a.cpp b.cpp files and a ch file Both cpp files include a ch file The header file contains a bunch of const int definitions and when I compile them I get no errors and still I can access these constants as if they were global variables. So the question is, why don't I get any compilation errors if I have multiple constant definitions and also those int constants are globally scoped?
source to share
This is because a const
namespace-scoped declaration implies internal binding. An internally linked object is only available within the translation unit in which it is defined. So, in a sense, the one const
object you have in c.h
is actually two different objects: one internal to a.cpp
and one internal to b.cpp
.
In other words,
const int x = ...;
equivalent to
static const int x = ...;
and
int x;
looks like
extern int x;
because non const
-namespaced declarations imply external binding. (In this latter case, they are not actually equivalent. extern
, And also by explicitly specifying an external link, produces a declaration, not an object definition.)
Note that this is specific to C ++. In C, const
does not change the implied link. The reason for this is because the C ++ committee wanted you to be able to write
const int x = 5;
in the title. In C, this header included from multiple files will lead to linker errors because you will be defining the same object multiple times.
source to share
From the current C ++ standard ...
7.1.1 Storage class specifications
7) A name declared in the scope of a namespace without a storage class specifier is externally related, unless it is internally related due to the previous declaration and provided that it is not declared const. Objects declared as const rather than explicitly declared extern have internal linkage.
3.5 Program and communication
2) If a name has an internal reference , the object it denotes can refer to names from other fields in the same translation unit .
The preprocessor causes the elements defined in the headers to be included in the current translation unit.
source to share