How do I load shared libraries at runtime on Linux in C++?

In C++, you can load shared libraries at runtime using the `dlopen` function from the `` header. This allows you to dynamically link libraries during the execution of your program, which can be useful for plugins, modular applications, or to reduce the initial size of a binary.

The process involves using `dlopen` to load the library, `dlsym` to obtain pointers to the functions you wish to use, and `dlclose` to close the library once you're done with it.

Here is an example demonstrating how to load a shared library at runtime:

#include <iostream> #include <dlfcn.h> typedef void (*FunctionType)(); int main() { void* handle = dlopen("libmylibrary.so", RTLD_LAZY); if (!handle) { std::cerr << "Cannot load library: " << dlerror() << std::endl; return 1; } dlerror(); // Clear existing errors FunctionType myFunction = (FunctionType) dlsym(handle, "myFunction"); const char* dlsym_error = dlerror(); if (dlsym_error) { std::cerr << "Cannot load symbol 'myFunction': " << dlsym_error << std::endl; dlclose(handle); return 1; } myFunction(); // Call the function dlclose(handle); // Close the library return 0; }

C++ dynamic loading shared libraries dlopen dlsym runtime linking Linux