I am writing a library and wanted to be as C++ centric as possible, remembering the old adage "Macros are evil".
In a source file, I had the following definitions:
const std::string DATA_DIR_ENV_STR = "DATADIR"
const std::string DFLT_DATA_DIR = "../data"
/*
#define DATA_DIR_ENV_STR "DATADIR"
#define DFLT_DATA_DIR "../data"
*/
std::string getRootDirectory()
{
char * datastr_ = getenv(DATA_DIR_ENV_STR);
if (datastr_)
return std::string(datastr_);
return DFLT_DATA_DIR;
}
// Header file
std::string getRootDirectory();
I then had a singleton class that was initialized like this:
bool mySingleton::inited = mySingleton::initialize();
bool mySingleton::initialize(){
std::string rootdir = getRootDirectory(); // <-SEGV when using const std::string
}
The library compiled fine, but when I linked an application to it, the app always SEGV'd. I used gdb to track down the problem and to my shock/horror, the string variables DATA_DIR_ENV_STR and DFLT_DATA_DIR had not yet been initialized when they were been accessed during the static variable initialization.
In the end I simply used macros to get around the issue. BUT, I can't help wondering, is this a variation of the 'static variable initialization fiasco'?. Is there another way to resolve this without using macros?