tags:

views:

86

answers:

1

I am trying to design header only library, which unfortunately needs to have global static variable (either in class or in namespace).

Is there any way or preferred solution to have global static variable while maintaining header only design?

The code is here

+5  A: 

There are a couple of options. The first thing that came to my mind was that C++ allows static data members of class templates to be defined in more than one translation unit:

template<class T>
struct dummy {
   static int my_global;
};

template<class T>
int dummy<T>::my_global;

inline int& my_global() {return dummy<void>::my_global;}

The linker will merge multiple definitions into one. But inline alone is also able to help here and this solution is much simpler:

inline int& my_global() {
   static int g = 24;
   return g;
}

You can put this inline function into a header file and include it into many translation units. C++ guarantees that the reference returned by this inline function will always refer to the same object. Make sure that the function has external linkage.

sellibitze
+1 local static is the easiest way with global data, especially since the new C++0x standard will guarantee their correct initialization even in multithreaded application.
Matthieu M.