Shared libraries

Until now, we have linked statically. This means that when linking was done, every time we used one of the logging library functions in main, the code was copied from the log.o object file.

Principles of Dynamic Linking

When your operating system is running, certain functions could be called thousands of times in a minute. So when every function is statically linked, certain functions would be present many times. Much more efficient is dynamic linking: only a reference to a function is linked in a program. Then at runtime, the program would ask the operating system, "where can I find this function?" and the OS would point the program to the location of the (maybe only copy of the) function.

To make your program use dynamic linking, nothing needs to be done. It is the default setting on most systems that your compiler generates just the beforementioned references instead of copying the library code in your program. And since your standard libraries are all shared libraries, dynamic linking works completely transparent for the common programmer.

Making a shared library

To enable dynamic linking on your own library, you have to compile it into a special type of object file. This special format is called ELF: Executable and Linking Format. It is the default binary format for executables used by SVR4, Solaris 2.x and Linux 2.x.

Below is an example, where it is assumed that the library log.c is compiled into an ELF library:

 $ gcc -fPIC -c log.c
 $ gcc -shared -Wl,-soname, -o log.o
 $ ln -s
 $ ln -s liblog

Line 1 compiles log.c to an object file, in a way that it can be dynamically linked. Line 2 says to produce a shared object, along with some parameters for the linker. Line 3 and 4 make links to the library. This is so that when you compile the program which uses your library just can include liblog and not an obscure

Note the version numbers. A convention is to give your library a major first version number and a minor second version number. When your library has undergone a major revision and makes it incompatible with the previous version, change the major number. Of course, the link liblog now should be updated to point to the new version.

To conclude; some handy utilities when working with libraries are: