views:

16

answers:

1

I've got the following h file:

#ifndef GLOBAL_DATA_H_
#define GLOBAL_DATA_H_

class GlobalData
{
  public:
    GlobalData();
    ...
  private:
    ...
};

namespace global_data
{
  static GlobalData globalDataInstance;
}

#endif

Countless files include the header file above, and access global_data::globalDataInstance. If I put a breakpoint in GlobalData's constructor body, I see that, when I run the application, the constructor gets called countless times. Why is this?

A: 

It appears that declaring static variables within a namespace does not do what I thought, according to this post:

http://bytes.com/topic/c/answers/134682-initializing-static-variable-inside-namespace

If you include this header in more than one source file you will get multiple variables. If you change the value of the variable in one file you will not see the change in another file.

It appears the property thing to do would be to declare the namespace variable using extern instead of static.

inajamaica