Search code examples
c++symbolsdylib

Can a runtime shared library call existing symbols?


I have:

  • Application A
  • Dynamic library D
  • Static library S

Where:

  • A is linked with static library S at compile time.
  • D is compiled without linking S, but uses its header files
  • A uses dlopen to load D at runtime.

Is it possible for D to use symbols defined in S when being run in A, without D being linked with S at its own compile-time? I.e. can D access symbols in the global namespace?

Other notes: I need D and A to both be able to call functions from S. I ideally don't want to alter S.

I've tried this, and I get (when a symbol from S is used in D):

dyld: lazy symbol binding failed: Symbol not found: __Z14myFunctioni

I presume this could either be:

  1. The existing function 'myFunction(int)' is not available to the shared library (security?)
  2. The symbol name for this function has been name mangled in a different way (EDIT: tested with extern "C" and ruled this out).

Perhaps I need to compile with different settings, or I have to always link all of S into D? Also would the situation changed if S became a dynamic library itself?

Thankyou


Solution

  • External references in the library are resolved using the libraries in that library's dependency list and any other libraries previously opened with the RTLD_GLOBAL flag. If the executable was linked with the flag "-rdynamic" (or, synonymously, "--export-dynamic"), then the global symbols in the executable will also be used to resolve references in a dynamically loaded library.