top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Accessing file-scope variable from shared library ctor in C++

+1 vote
431 views

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 
#include 
static std::string myPath;

__attribute__((constructor))
void SetPath() {
 Dl_info dl_info;
 dladdr((void*)SetPath, 
 myPath = dl_info.dli_fname; // 

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?

posted May 31, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

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.)

answer May 31, 2013 by anonymous
Similar Questions
+3 votes

What are the preconditions on C++ type that allows its use in shared memory or read from a file descriptor?

+2 votes
#include <iostream>
#include <stack>

using namespace std;
int main ()
{
        stack<int> mystack;
        mystack.push(10);
        mystack.push(20);
        mystack.top() -= 5;
        cout << mystack.top() << endl;
        return 0;
}
...