I have a shared library that I implement and I want the .so to call a function in the main program that loads the library.
Let's say I have main.c (executable) which contains:
void inmain_function(void*);
dlopen("libmy.so");
In the my.c (the code for the libmy.so) I want to call inmain_function
:
inmain_function(NULL);
How can the shared library call inmain_function
regardless the fact inmain_function
is defined in the main program.
Note: I want to call a symbol in main.c from my.c not vice versa which is the common usage.
You'll need make a register function in your .so so that the executable can give a function pointer to your .so for it's later use.
Like this:
the register_function needs to store the function pointer in a variable in the .so where the other function in the .so can find it.
Your mylib.c would the need to look something like this:
Put your main function's prototype in a .h file and include it in both your main and dynamic library code.
With GCC, simply compile your main program with the
-rdynamic
flag.Once loaded, your library will be able to call the function from the main program.
A little further explanation is that once compiled, your dynamic library will have an undefined symbol in it for the function that is in the main code. Upon having your main app load the library, the symbol will be resolved by the main program's symbol table. I've used the above pattern numerous times and it works like a charm.
The following can be used to load a dynamic library in your code (in case somebody came here after looking at how to do that):
Don't forget to put
#include <dlfcn.h>
and link with the–ldl
option.You might also want to add some logic that checks if
NULL
is returned. If it is the case you can calldlerror
and it should give you some meaningful messages describing the problem.Other posters have however provided more suitable answers for your problem.
You have two options, from which you can choose:
Option 1: export all symbols from your executable. This is simple option, just when building executable, add a flag
-Wl,--export-dynamic
. This would make all functions available to library calls.Option 2: create an export symbol file with list of functions, and use
-Wl,--dynamic-list=exported.txt
. This requires some maintenance, but more accurate.To demonstrate: simple executable and dynamically loaded library.
Library code (lib.c):
So, first build the library (this step doesn't differ):
Now build executable with all symbols exported:
Run example:
Symbols exported:
Now with the exported list (
exported.txt
):Build & check visible symbols: