Blogroll

Tech Travels

Menu

Widgets

Search

C/C++ dynamic library

Sometimes ago October 2005, I was playing with C/C++ just to refresh what school taught me. And as a FSF fan I was using the gcc compiler (via command line). So after the very first very easy attempts I stumbled in the dynamic library.

Dynamic (or shared) library are those part of code that isn’t included in the binary executable. In compiling time, the linker verify the program’s required symbols and bind them with the shared library. During the execution time, the dynamic loader, check which libraries are required by the program, load them into memory (if they weren’t already) and then “attach” the copy of the executed program.

This dinamyc load slow down a bit the application startup, but you’ll get the advantages of getting a lighter binary, use less RAM resources (many programs access the same shared library), and in case of error in the library, fix them and recompile the library will solve the error in all applications who’s using it.

In order to compile a shared library, you need to compile it for Position Independent Code (PIC). This because when you create the library, you wont know in which position of memory the library will be inserted for the program who’s using it, so all callings have to be done in relative way, not absolute. The g++ option to obtain this code is -fpic.

When compiling a shared library, you’ll need to compile them for different architectures, to obtain this the g++ option to use is -shared.

So let’s say we have mickey.cc and mouse.cc files and we want to create the miceland library, the command to use is something similar to

If we need it, it’s possible to set this new directory (were the library actually reside) as a system’s directory for libraries: just add it to the /etc/ld.so.conf file and then use the ldconfig program (all as root).

It is also possible in compilation time to tell to the program where to find the library. This is achieved with the -rpath flag:

The priorities with witch the dynamic loader search for the library are -rpath, LD_LIBRARY_PATH, /etc/ld.so.conf

If in the same directory there’s a static and a dynamic library with the same name, the loader will prefer the last one. You can tell it to prefer the static one if you compile with the -static option.