Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

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.
[188 byte] By [mailbox_abhishe] at [2007-11-11 8:27:06]
# 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.
Nokia2280 at 2007-11-11 21:01:25 >
# 2 Re: Static Variable
You should never put static variables in a header file because the header file may be included multiple times in the same program. You should define static and global objects in a .cpp file.
Danny at 2007-11-11 21:02:20 >
# 3 Re: Static Variable
Oh!! I thought you were on vacation. :D
Nokia2280 at 2007-11-11 21:03:18 >
# 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 >
# 5 Re: Static Variable
scope of static variable is local to the file in which it is declared. So whenever include a header file in ur program it will create a private copy of that variable local to that file. The thing is that why to declare static variable in the file if its of no use.
mchandel at 2007-11-11 21:05:29 >
# 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 >