top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration
Print Preview

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

+1 vote
54 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 Google+ Share Button LinkedIn Share Button Multiple Social 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;
}

Useful Links with Similar Problem
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#470/147, 3rd Floor, 5th Main,
HSR Layout Sector 7,
Bangalore - 560102,
Karnataka INDIA.
QUERY HOME
...