Monday, May 24, 2010

Static variable?

//Source a.h


#include %26lt;iostream.h%26gt;


void fn();


static int z;





//Source a.cpp


#include "a.h"


void main()


{


z = 10;


fn();


}


//source b.cpp


#include "a.h"


void fn()


{


cout%26lt;%26lt;z;


}





1)After i link a.o and b.o, why am i not able to get the value of z in fn() although it is a static variable and its value is being set in a.cpp ?


2) if i dont declare the variable z as static , it is giving link error


saying that it is a duplicate symbol. why is this? by not declaring z as static i wanted to have global variable for each source file. why isnt this possible.

Static variable?
The static keyword in C has different meaning depending on the context. When applied to a global symbol, the static keyword disallows the linker to expose the modified symbol to other object files.





Without the static keyword each time a.h is included the linker will export "z" in the given object file. When two ore more object files that have included a.h are linked together, the linker will abort with an error, as the symbol is being defined in every source file that includes a.h.





Declaring the symbol static has the opposite effect. Each instance will be invisible outside of the object file.





What you want to do is defined it as an actual symbol in at most one source file, and else where use the extern modifier. Put a declaration in the header file with the exten keyword, and redefine the symbol in at most file of the files.
Reply:You can't pull it into both a.cpp and b.cpp with the same definition. It has to be declared global in one and extern in the other (in fact, in all others). Try using conditional compilation to decide which one gets to own it.





This is a classic situation.


No comments:

Post a Comment