I have a function which calls an initialization routine statically. This is needed for a pluginsystem where the plugin is either dynamically loaded (which works fine) or can also be statically linked. Since the static plugin is not known to the main application it must register itself, so that the main app knows about it (just like it were a dynamically loaded plugin).
The problem now is that the initalization is never called. However, when I add a dummy function and call it from the main app, then the initializer is suddenly called. So this looks to me as if the initalization is "optimized" away from gcc.
static bool registerPlugins(void)
{
std::cout << "Registering CSV static plugin ... " << std::endl;
PluginManager::registerStaticPlugin(&PluginInfo);
return true;
}
static bool gCSVRegistered = registerPlugins();
The text "Registering..." is never printed, but adding the dummy function
void helper(void)
{
std::cout << "Registered: " << gCSVRegistered << std::endl;
}
... and call it dfrom the main app, then all the exptected text is printed.
So how can I force the static initalizer to not get thrown away???
I'm using Mingw32 with gcc 4.9.2 (just for the record :)).
Important update: The relevant code is in a static library. In this case it doesn't get triggered, only when the module is linked directly to the main application the initalizer is called.
SSCCE
main.cpp:
#include <iostream>
const char *gData = NULL;
int main()
{
if(gData)
std::cout << "Registration: " << gData << std::endl;
else
std::cout << "Registration: NULL" << std::endl;
return 0;
}
void registered(const char *pData)
{
gData = pData;
}
static1.cpp
void registered(const char *pData);
static bool registration(void)
{
registered("Static initializer 1");
return true;
}
static bool reg = registration();
static2.cpp
void registered(const char *pData);
static bool registration(void)
{
registered("Static initializer 2");
return true;
}
static bool reg = registration();
static library: lib_main.cpp
void registered(const char *pData);
static bool registration(void)
{
registered("Static initializer library");
return true;
}
static bool reg = registration();