I need to define module name somehow for each of my static libraries and a project that uses them. I cannot to do this simply as:
std::string const module_name = "my module";
because I need this value during static members initialization. Since static data initialization order is not defined, my module_name
variable can be still uninitialized while I'm trying to use it.
To resolve this problem I defined
inline std::string const& module_name()
{
static std::string const name = "my module";
return name;
}
for each module. But this doesn't work because all module_name()
calls was resolved to use implementation from the parent module (module_name()
always returns the name of the parent executable project). And I don't understand why. I hoped that since this inline function is defined and used in a static library, actual module name should be captured. Is it because this function wasn't inlined by compiler?
Is there any recommended way to resolve this problem?
compiler: VC++10 and gcc, tested on VC++10
An entity with external linkage can only have one definition in a program, so it's not surprising you can't have multiple definitions of the same function in one program.
It's not to do with inlining, what happens is the linker sees multiple definitions of the same symbol (which often happens with template instantiations and inline functions, and other symbols when using dynamic libs) and picks one definition to use.
To make each libary have a separate definition you need them to have internal linkage, which can be done by making the function static or putting it in an unnamed namespace, or using platform-specific methods such as __dllimport
or __attribute((visibility("hidden")))
to tell the compiler the symbol is private to the shared library and should not be exported (and therefore won't be replaced by another definition of the same symbol.)
Alternatively, just put each module in its own namespace and put the function in that namespace, then each function is different and they won't interfere.