C++ Shared Library: Dynamic Loading (Eps: 2)
Hello good coder! Long time no see, and here we are back with a new story about C++! Continuing from the previous story, we will learn about dynamic loading here. In the simplest terms, dynamic loading means calling a function from outside our code in runtime, while in dynamic linking, the “called function” is already known at compile time. There are many better definitions of this on the internet, so you should check out more!
Code
Dynamic loading in C++ is done by utilizing a library called dlopen (UNIX) or libloaderapi (Windows). It is a simple library that checks if a targeted function exists so that we can use it afterward. Three main parts to call using that library are: dlopen(), dlsym(), dlclose()
or LoadLibrary(), GetProcAddress(), FreeLibrary()
. The term “symbol” can be interpreted as a function, variable, or class from the external shared library.
The code above is already self-explanatory. The flows are:
- Call
dlopen
- Call
dlsym
- Use the symbol, or in this case, our symbol is a function called func
- Call
dlclose
“your-external-lib.so” (line 9) is a shared library file that contains a symbol/function called “yourExternalSymbolFunc” (line 18). Again, in our case, the symbol is a function, though you could also make the symbol a variable or class.
Below is an example of the shared library code. Don’t forget to compile it into a shared library (.so file)
extern "C" {
int yourExternalSymbolFunc() {
printf("Enter external\n");
return 123;
}
}
Command
Compile the shared library, which contains the targeted symbol/function.
g++ -fPIC -shared your-external-lib.cpp -o your-external-lib.so
Compile the main code.
g++ main.cpp -ldl -o main.o
RUN
LD_LIBRARY_PATH=. ./main.o
Thanks for reading my story about dynamic loading in C++. I was hoping you could read my previous episode about dynamic linking here. See you 👋