Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap