I would like to know what is the difference between static variables in a header file vs one declared in a class.
When a static variable is declared in a header file is its scope limited to .h file or across all units. Generally, a static variable is initialized in a .cpp file when declared in a class, right? Does that mean a static variable scope is limited to two compilation units?
Excuse me when I answer your questions out-of-order, it makes it easier to understand this way.
There is no such thing as a "header file scope". The header file gets included into source files. The translation unit is the source file including the text from the header files. Whatever you write in a header file gets copied into each including source file.
As such, a static variable declared in a header file is like a static variable in each individual source file.
Since declaring a variable
staticthis way means internal linkage, every translation unit#includeing your header file gets its own, individual variable (which is not visible outside your translation unit). This is usually not what you want.In a class declaration,
staticmeans that all instances of the class share this member variable; i.e., you might have hundreds of objects of this type, but whenever one of these objects refers to thestatic(or "class") variable, it’s the same value for all objects. You could think of it as a "class global".Yes, one (and only one) translation unit must initialize the class variable.
As I said:
staticmeans completely different things depending on context.Global
staticlimits scope to the translation unit. Classstaticmeans global to all instances.PS: Check the last paragraph of Chubsdad’s answer, about how you shouldn’t use
staticin C++ for indicating internal linkage, but anonymous namespaces. (Because he’s right. 😉 )