Dynamic libraries

What is a library and why to use it?

Dynamic libraries

Creating a Dynamic Library

  1. First we need to create the object files (.o). For this we need to compile our library source code (.c) into position-independent code (PIC), so we must use the compiler flag -fPIC and the -c option in Linux gcc. The line showed below will create the object files for all the .c files in the current directory.
$ gcc -c -fPIC *.c
myfunction1.c myfunction2.c myfunction3.c
myfunction1.c myfunction2.c myfuntion3.cmyfunction1.o myfunction2.o myfunction3.o
$ gcc -shared -o libmylibrary.so *.o

Using a dinamyc library

  • Compile time. We must tell the linker to scan the shared library while making the executable program, so that it is sure there are no missing symbols. It won’t actually take the object files from the shared library and insert them into the program.
    To do this in Linux gcc, the -L argument is used to define the path, and -l is used for the library name without the “lib” prefix and without the “.so” suffix. Here is an example:
$ gcc main.c -L. -lmylibrary -o program1
  • Run time. When we run the program we need to give the loader a little help to find the shared library. We can use the environment variable LD_LIBRARY_PATH for this. The way to do that depends on the type of shell we use (‘tcsh’ and ‘csh’, versus ‘sh’, ‘bash’, ‘ksh’ and similar shells), as well as on whether or not “LD_LIBRARY_PATH” is already defined. To check if this variable is defined, we type:
$ echo $LD_LIBRARY_PATH
$ export LD_LIBRARY_PATH= /full/path/to/library/directory:$LD_LIBRARY_PATH
$ ldd program1

Static libraries vs. Dynamic libraries

  • A static library is “inserted” within our executable, which means that we can take it to another computer without fear of missing libraries.
  • But if the libraries have a bug and a version appears that fixes that bug, you have to recompile the code
  • The executable is larger because they have the libraries included within the executable.
  • These are faster to execute because the functions are inside the executable, so we don’t have to look for them.
  • A dynamic library is not inserted into our executable so our executable will be smaller.
  • But if we take our executable to another machine, the libraries have to go with it.
  • The execution is slower because the library must be searched outside the executable.
  • If there is a bug in the library and a version appears that fixes that bug, this is updated and fixed in all executables that use it.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store