RE: Accessing file-scope variable from shared library ctor

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

 



> #include <string>
> #include <dlfcn.h>
> 
> const std::string& GetPath();
> 
> namespace {
> std::string reallyGetPath() {
>      Dl_info dl_info;
>      dladdr((void*)GetPath, &dl_info);
>      return dl_info.dli_fname;
> }
> }
> 
> const std::string& GetPath() {
>    static const std::string myPath = reallyGetPath();
>    return myPath;
> }
> 
> The compiler adds locking to the initialization of myPath.

Everyone, thank you for the replies and help.  Jonathon, I did, eventually, take the advice given.  I really didn't want to lose the "discovery of path on initialization of the library" and that's why I posted as I did last week.  I realized, however, that all of this was very much in vain.  Also, I have been reeducated in something which I had completely forgotten.  That is, I'd forgotten that the compiler initializes static function variables only once as is depicted above.  The solution I wrote has an extraneous conditional in it (the very thing I wanted most to avoid).

I have one question further.  I tried using this approach because of what I read in the GCC manuals, "Functions with these attributes are useful for initializing data that is used implicitly during the execution of the program. (taken from http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html)"  I wish only to understand more fully, if initialization of data, as in this case, is so problematic, why is it such a good thing?  Is it because my data variable wasn't truly global, but instead translation-unit-only?  What am I missing from what the manual is describing?

Thanks for all the help.

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