Static Variable
Hi,
Can any body tell me whether is it ok if we declear a static variable in a header file ? in which scenario we should avoid these thing i.e using static variable in C Header file.
# 1 Re: Static Variable
Can any body tell me whether is it ok if we declear a static variable in a header file ? in which scenario we should avoid these thing i.e using static variable in C Header file.
Put your static variables in *.c file.
Put into header files (which will be used by many other files) only those things you wish to export.
# 4 Re: Static Variable
Agreed that you should put it in the cpp, but since its static, does the compiler only declare it once ? I.E. no multiple include problems if you DO put in the header? I would just try it and see but I dont trust modern compilers to bomb on incorrect code -- often, illegal stuff works just fine.
jonnin at 2007-11-11 21:04:19 >

# 6 Re: Static Variable
Agreed that you should put it in the cpp, but since its static, does the compiler only declare it once ? I.E. no multiple include problems if you DO put in the header? I would just try it and see but I dont trust modern compilers to bomb on incorrect code -- often, illegal stuff works just fine.
This is a fundamental concept of C/C++: you can declare the static variable multiple times. You must define it only once. That's why you must separate the definition from the declaration. If the definition occurs mutiple times in different sources, you *will* get multiple copies of the same static variable which could lead to linker errors if the linker is smart enough, or other bugs that are much worse. Think of functions: you can declare them many times, but you must define them only in one place. inline functions are trickier, they can be defined in several places (i.e., in every .cpp file that includes a .h file with a definition of the inline function) but in this case there are (usually) no multiple copies because the function, once inlined, is no longer a function.
Danny at 2007-11-11 21:06:22 >
