Monday, September 5, 2011

[C++] Declare a external (global) variable in header file

If you declare a global variable (in order to share within multifile program) in header file such as:
 int tom = 3;    // declare in header file
It 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:
extern int tom;
then, define the value of variable in only one c file:
extern int tom = 3;
On the other hand, declare a global constant in header file such as:
const int tom = 3; // declare in hearder file 
It 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

Fork me on GitHub