Skip to content

About Dynamic Libraries

Posted on:May 26, 2023 at 11:22 AM

While working in C or C++, you may have come across header files and you may wonder where all the code is. If you open up stdio.h, you won’t see the definition of printf or puts, just their headers. Here static libraries come. Static libs are compiled pieces of code that contain declarations of functions, which are linked at compile time. They usually have an .a suffix.

There is another branch of libraries that is called dynamic linked libraries. As the name suggest, they aren’t linked at compile time, but loaded at run time. For example, using the dlsym tools, you can load any library.

The process of loading a function is quite simple. First, you should load the whole module and then find the function pointer(address) of the function in the module.

    void *lib_handle = dlopen("./mylib.so", RTLD_LAZY); // load the module
    typedef void (*HelloWorldFunc)();
    HelloWorldFunc hello_func = (HelloWorldFunc)dlsym(lib_handle, "hello_world"); // get the symbol address
    hello_func();