Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Apr 13, 2004



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Static Variable Declarations in Header Files

Ever declared a static variable in the header file at the file scope and had it introduce completely different behavior than you thought it would?

This is because when you include the header file in more than one .CC file, more than one instance of the variable gets created at each .CC file scope. Obviously, you should never declare a static variable at the file scope unless you want to have a copy for each file that includes the header file.

If you want only one instance, declare the static variable at the class scope as follows:

  • In globals.h:
    Class globalAccess {
        static int globalA;
  • In globals.cc:
    int globalAccess::globalA = 0;
  • In userfiles:
    - Include the globals.h
    - Access the globalA by globalAccess::globalA
Selva Somasundaram
Thanks for your registration, follow us on our social networks to keep up-to-date