Receive “undefined symbol” error when loading library with dlopen

dlopenshared-libraries

I'm writing some code that uses dynamic shared libraries as plugins.

My command line for building the shared libraries looks like:

cc -shared -fPIC -o module.so -g -Wall module.c

Within the module, I can call functions that are in any other shared library that has been loaded within the main executable.

However I cannot access (exported) functions that are in the executable itself (I get undefined symbol errors).

My call to dlopen looks like this:

void *handle = dlopen(plugin, RTLD_NOW);

Can anyone please advise how my module can call back to my executable, without having to put all of the executable's utility functions into yet another shared library?

Best Solution

Correct solution is to add -rdynamic to the link command of the main executable. This will add appropriate option to ld (which, when using GNU ld, happens to be --export-dynamic).

Adding --export-dynamic directly is technically incorrect: it's a linker option, and so should be added as -Wl,--export-dynamic, or -Wl,-E. This is also less portable than -rdynamic (other linkers have an equivalent, but the option itself is different).

Related Question