I'm writing a header-only logger library and I need global variables to store current logger settings (output flags, log file descriptor etc.). My thoughts:
Is there any variants i didn't consider yet? Is there any other way to have global variables using headers only.
p.s. I'm looking for both c99/c++11 compatible solution with possible gcc hacks (gcc >= 4.8)
One approach is to hide options behind a function that returns a reference to a local static option. As long as the ODR is not violated (e.g. by some macro-dependent changes of the functions), it is guaranteed that the local static variables are unique across your program. As a simple example, this can be in the header file:
inline bool& someOption()
{
static bool opt = false;
return opt;
}
and in a translation unit:
someOption() = true;
It would probably be useful to group your options into a struct and apply the above technique to an instance to this struct.
Note that this approach is limited to C++ (thanks to @rici for the hint), and might only accidently work out in C using gcc.