Excuse me when I answer your questions out of order, this makes it easier to understand.
When a static variable is declared in the header file, its scope is limited to the .h file or all units.
There is no such thing as a "file header area". The header file is included in the source files. A translation block is a source file that includes text from header files. Everything that you write in the header file is copied to each of them, including the source file.
Thus, the static variable declared in the header file is similar to the static variable in each individual source file.
Since declaring a static variable in this way means internal binding, each unit of translation #include in your header file gets its own variable , individual (which is not visible outside your translation unit). This is usually not what you want.
I would like to know what is the difference between static variables in vs header file declared in class.
In a class declaration, static means that all instances of the class share this member variable; those. you can have hundreds of objects of this type, but whenever one of these objects refers to a static variable (or "class"), this is the same value for all objects. You might think of it as a "global class."
Typically, a static variable is initialized in a .cpp file if it is declared in the class correctly?
Yes, one (and only one) translation unit must initialize a class variable.
So, what does it mean that the scope of a static variable is limited to two compilation units?
As I already said:
- The header is not a compiler,
static means completely different things depending on the context.
Global static limits the scope of translation. The static class means global for all instances.
Hope this helps.
PS: Check out the last paragraph of Chubsdad's answer on how you shouldn't use static in C ++ to specify internal binding, but anonymous namespaces. (Because he is right. ;-))
DevSolar Sep 13 '10 at 6:19 2010-09-13 06:19
source share