Just for the purpose of learning, I've made a small example of a main program tentatively loeading a shared library via dlopen
(and then a symbol from it via dlsym
) and using a default one if the former is not avalable.
On my machine, to make the non-default library available to the main program, I need to compile the former via g -fPIC -shared MyLib.cpp -o libMyLib.so
, whereas both main.cpp
and DefaultLib.cpp
are compiled simply by g -c main.cpp -o main.o
and g -c DefaultLib.cpp -o DefaultLib.o
. How can I provide the options -fPIC -shared
to the compilation of MyLib.cpp
in Compiler Explorer?
The current attempt is here, where, I believe, MyLib.cpp
is compiled just like the other two cpp
files, i.e. without providing options -fPIC
and -shared
, and maybe most importantly without generating a file with the name libMyLib.so
, thus resulting dlopen
failing to load; indeed, the foo
from the other, default library DefaultLib
is called.
CodePudding user response:
Can I compile and dlopen a dynamic library in Compiler Explorer?
Yes, it's certainly possible.
In CMakeLists.txt
:
add_library(MyLib SHARED MyLib.cpp)
...and remove MyLib.cpp
from add_executable
.
Then in main.cpp
:
void * lib = dlopen("build/libMyLib.so", RTLD_LAZY);
Because the library is placed in the build
subdirectory.