0

Is it possible have a global variable defined inside an application, accessed by a shared library that has been loaded with dlopen()?

I have it declared as an extern but when the app loads and tries to use it I get an undefined symbol error.

I am loading the library with flags set to RTLD_LAZY | RTLD_GLOBAL.

hqt
  • 29,632
  • 51
  • 171
  • 250
hookenz
  • 36,432
  • 45
  • 177
  • 286
  • hmm, looks like I might be able to provide a getter for the symbol by a function I can place in the app that loads the library. – hookenz May 29 '14 at 03:18
  • Wait, is the global variable actually defined in the library, or in the application? Did you define it extern in the application? – nneonneo May 29 '14 at 05:21
  • It's a global defined inside the app but defined as an extern in the library itself. – hookenz May 29 '14 at 20:05

1 Answers1

3

You have to you build your application where you have a global variable with -rdynamic option for g++. This option instructs the linker (ld) to add all symbols, not only used ones, to the dynamic symbol table of your application.

This is an example how I build my test C++ application that loads a shared library. The shared library uses a global variable in main.cpp. So I have added -rdynamic when build my main application:

g++ -rdynamic  -m64 -g main.cpp -o main -ldl

When g++ finds -rdynamic it passes the flag -export-dynamic to the ELF linker (ld). This is from man ld (which actually creates the dynamic symbol table):

If you use "dlopen" to load a dynamic object which needs to refer back to the symbols defined by the program, rather than some other dynamic object, then you will probably need to use this option when linking the program itself.

Useful links: