Re: Accessing file-scope variable from shared library ctor

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

 



On 31/05/13 22:45, Andy Falanga (afalanga) wrote:
> 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
If you only want to avoid calculation multiple times when calling an
accessor, why not lazy-load it?

Something like:

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

const std::string& GetPath() {
   static std::string myPath;
   static bool loaded = false;
   if (!loaded) {
     Dl_info dl_info;
     dladdr((void*)GetPath, &dl_info);
     myPath = dl_info.dli_fname;
     loaded = true;
   }
   return myPath;
}
(You will need to add some locking code if it can be called at the same
time from several threads)

That costly path will be accessed only once (on the first call), with
the other calls just returning the cache value, as you wanted. It also
has the benefit that if the function is never called, you don't need to
load the path.





[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