c++ - Global variable has multiple copies on Windows and a single on Linux when compiled in both exec and shared libaray -
* question revised (see below) *
i have cpp file defines static global variable e.g.
static foo bar;
this cpp file compiled executable , shared library. executable may load shared library @ run time.
if on linux there seem 2 copies of variable. assume 1 comes executable , 1 shared library. other platforms (hp, windows) there seems 1 copy.
what controls behavior on linux , can change it? example there compiler or linker flag force version of variable shared library same 1 executable?
* revision of question *
thanks answers far. on re-examining issue not problem stated above. static global variable above indeed have multiple copies on windows, no difference see on linux.
however, have global variable (not static time) declared in cpp file , extern in header file.
on windows variable has multiple copies, 1 in executable , 1 in each dll loaded up, , on linux has one. question difference. how can make linux have multiple copies?
(the logic of program meant value of static global variable dependent of value of non-static global variable , started accusing wrong variable being problem)
i suggest read following. afterwards, understand shared libraries in linux. said others, quick answer static
keyword limit scope of global variable translation unit (and thus, executable or shared library). using keyword extern
in header, , compiling cpp containing same global variable in 1 of modules (exe or dll/so) make global variable unique , shared amongst modules.
edit: behaviour on windows not same on linux when use extern
pattern because windows' method load dynamic link libraries (dlls) not same , incapable of linking global variables dynamically (such 1 exists). if can use static loading of dll (not using loadlibrary
), can use following:
//in 1 module has actual global variable: __declspec(dllexport) myclass myglobalobject; //in other modules: __declspec(dllimport) myclass myglobalobject;
this make myglobalobject
unique , shared amongst modules using dll in first version of above used.
if want each module have own instance of global variable, use static keyword, behaviour same linux or windows.
if want 1 unique instance of global variable , require dynamic loading (loadlibrary
or dlopen
), have make initialization function provide every loaded dll pointer global variable (before used). have keep reference count (you can use shared_ptr
that) such can create new 1 when none exist, increment count otherwise, , able delete when count goes 0 dlls being unloaded.
Comments
Post a Comment