The static
keyword on a global variable gives that variable internal linkage. It means that any translation unit that has that definition will have its own copy of the object. So the a
object that main.cpp
sees and that FileA.cpp
sees are different objects. change
will modify one of them, but main
will output the other.
If you were intending static
to mean that the object has static storage duration, global variables (or variables at namespace scope in general) have static storage duration anyway. You don't need to mark them static
. However, if you remove static
, you'll have another problem; you'll have multiple definitions of a
across translation units.
The correct way to do this is to declare a
as extern
in the FileA.hpp
file:
extern int a;
Then in a single translation unit (probably in FileA.cpp
, define the object:
int a;
This means that any object that includes FileA.hpp
will have the declaration of a
(which is fine) and only one translation unit will have the definition of a
. Perfect.