This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Accessing file-scope variable from shared library ctor


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 Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]