RE: Accessing file-scope variable from shared library ctor

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

 



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

Florian,

You've spoken what's taken me a few hours to find on my own.  I've attempted to fix this with things like:

#include <string>
#include <dlfcn.h>

namespace {
	std::string myPath __attribute__((init_priority(101)))("");
	__attribute__((constructor(102)))
	void SetPath() { ... }
}

This worked wonderfully in my much smaller test bed program: a single shared library and a test driver program.  However, when I happily applied these changes to the larger project, a hundred or more translation units all getting wrapped into a single DLL, I was right back where I started: segfault city.  Needless to say, the happiness didn't last long.

Is there some way of putting this into a constructor type function that will execute on loading the library?  I want to avoid calling something to determine the path hundreds of times during execution when it won't be necessary.  Thanks for the help too.

Andy





[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