Re: Accessing file-scope variable from shared library ctor

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 05/31/2013 06:51 PM, Andy Falanga (afalanga) wrote:
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?

Use a C++ constructor. Execution order will follow definition order in the same translation unit. But between translation units, ordering might still not be consistent with tour requirements, so you might still face the same issue in the end. Therefore, it is often better to use a static variable in a function, where the initialization happens in user-defined constructor.

(GNAT automatically finds a suitable global initialization order if such an order can be determined statically at all.)

--
Florian Weimer / Red Hat Product Security Team




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux