c++ - static variable cpp do not want to change -
filea.hpp: static int a; void change(int); filea.cpp #include "filea.hpp" void change(int x) { = x; } main.cpp #include "filea.hpp" #include <cstdlib> #include <iostream> int main() { = 5; std::cout<<a<<std::endl; change(10); std::cout<<a<<std::endl; = 20; std::cout<<a<<std::endl; system("pause"); return 0; }
my output is:
5 5 20
can me this? why variable 'a' don't want change in function in filea.cpp. how fix this. when make change(int x) inline in "filea.hpp" works fine.
the static
keyword on global variable gives variable internal linkage. means translation unit has definition have own copy of object. a
object main.cpp
sees , filea.cpp
sees different objects. change
modify 1 of them, main
output other.
if intending static
mean object has static storage duration, global variables (or variables @ namespace scope in general) have static storage duration anyway. don't need mark them static
. however, if remove static
, you'll have problem; you'll have multiple definitions of a
across translation units.
the correct way declare a
extern
in filea.hpp
file:
extern int a;
then in single translation unit (probably in filea.cpp
, define object:
int a;
this means object includes filea.hpp
have declaration of a
(which fine) , 1 translation unit have definition of a
. perfect.
Comments
Post a Comment