C++ Shared Library: Dynamic Loading (Eps: 2)

Muhammad Naufal Pratama
2 min readDec 14, 2024

--

Photo by Luca Bravo on Unsplash

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:

  1. Call dlopen
  2. Call dlsym
  3. Use the symbol, or in this case, our symbol is a function called func
  4. 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 👋

--

--

Muhammad Naufal Pratama
Muhammad Naufal Pratama

Written by Muhammad Naufal Pratama

Specialist wanna-be, Generalist in reality 🃏

Responses (1)