int tom = 3; // declare in header fileIt would be wrong, because variable will redefine in multiple c files when you include header file in them.
The right way is use extern keyword that let compile know it is a global variable:
First,in header file, declare variable:On the other hand, declare a global constant in header file such as:
extern int tom;
then, define the value of variable in only one c file:
extern int tom = 3;
const int tom = 3; // declare in hearder fileIt is also wrong, but it is because program do not share the same variable in all files. Quote from "C++
Primer Plus, Fifth edition":
The reason is that, in C++ (but not C), the const modifier alters the default storage classes slightly. Whereas a global variable has external linkage by default, a const global variable has internal linkage by default. That is, C++ treats a global const definition, such as in the following code fragment, as if the static specifier had been used.
The right way to declare global const in header file is:
First,in header file, declare variable:
extern const int tom;
then, define the value of variable in only one c file:
extern const int tom = 3;
No comments:
Post a Comment