Accessing file-scope variable from shared library ctor

Andy Falanga (afalanga) afalanga@micron.com
Fri May 31 20:46:00 GMT 2013


Hi,

I have a need for certain functions in a shared library to know the path to that library in order to find various resources.  What I have in source.cpp:

#include <string>
#include <dlfcn.h>
static std::string myPath;

__attribute__((constructor))
void SetPath() {
    Dl_info dl_info;
    dladdr((void*)SetPath, &dl_info);
    myPath = dl_info.dli_fname; // <-- segfault when built with optimizations turned on
}

As the comment shows, when built with optimizations enabled, that line produces a segfault.  With no optimizations, it works just fine.  What magic must be done in order to ensure that this variable exists before the "constructor" function is called when loading the shared library?

What I've tried thus far:

// attempt to move variable into initialized data section, didn't work
// no surprise because the variable is in the .bss section when built
// without optimizations
static std::string myPath __attribute__((section("INITDATA")));

I also tried to prevent optimization for SetPath(): didn't work.
__attribute__((constructor))
__attribute__((optimize("O0")))
void SetPath() { ... }

I'm building on CentOS 6.2.  GCC tool chain 4.4.4 (yeah, I know, it's old but that seems to be the nature of the beast in CentOS).

Thanks,
Andy



More information about the Gcc-help mailing list