Skip to content
Advertisement

Global variables in header only library

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:

  • I can’t declare variables as extern, as i don’t have access to the translation units to define them
  • I can’t just define global variables in header as it will lead to multiple definitions
  • static variables in header’s functions may seem good at the first glance, but the fact is that every translation unit will have it’s own copy of ‘global’ variable, which is awkward and definitely wrong
  • I don’t also think it is possible to avoid global variables in my case (even though that’s what i’d like to do) as i obviously have to store settings somehow between log function calls

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)

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement