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.
Yes, it's certainly possible.
In
CMakeLists.txt:...and remove
MyLib.cppfromadd_executable.Then in
main.cpp:Because the library is placed in the
buildsubdirectory.Demo