jeudi 17 décembre 2015

Is it possible to avoid using of global variables if I need to share state between shared library calls?

I have a legacy shared library which exports methods Init(), DoSomething() and Release(). Init() method initializes the Config variable which is used across the dll calls.

Config* g_config = NULL;

extern "C" void __declspec(dllexport) Init(void)
{
    if (g_config == NULL) 
    {
       g_config = new Config("/path/to/config-file"); 
    }
}

extern "C" void __declspec(dllexport) DoSomething(char* data)
{
    if (g_config == NULL)
      throw std::runtime_error("Config is not initialized");

    std::vector<ConfigValue> configValues = g_config->readValues();
    ...
}

extern "C" void __declspec(dllexport) Release(void)
{
   if (g_config != NULL)
   {
      delete g_config;
      g_config = NULL;
   }
}

The main concern I have here is a global variable.

After reading a lot of discussions about the problems with global variables and Singletons I came to idea to eliminate the global variable in order to make code testable, but I'm not sure if it is possible.

Is there any approach that allows to avoid using of global variables?

Aucun commentaire:

Enregistrer un commentaire