What is the differences between static and dynamic libraries?

Elmustapha Abourar
3 min readMay 9, 2022

Static libraries vs. dynamic libraries: These are pre-compiled object codes which are used in the source code file to provide functionalities for a predefined function or user specified functions. There are two types of libraries that are widely used in C programming and in the Linux domain : static libraries and shared libraries.

Static Library :

The functions included in static libraries are included at compile time. When compiling a program, during the linking phase, the linker will produce an executable that includes the object code of all the functions in the library used. You should only use static libraries when you are not dealing with a large number of functions. The reason is that all functions are included in the executable, which increases the size of the file. However, it should be noted that having all functions already included in the executable will increase the execution speed when a function is referenced more than once.

To build the library, you must use the archive command with the flag rc . You should also include the name you want to give to the library beginning with lib and you should include and all the object files that should be in the library:

$ ar rc lifile.a file.o

The -r flag inserts the file members into the archive [liball.a].

The -c flag creates the archive [liball.a].

The *.o command acts upon all files with with the suffix .o [object files]

Dynamic Library :

This library, instead of the functions being included, actually exists outside the executable. With this particular library, the functions are made available at runtime. When dealing with a large number of functions, this library is the obvious way to proceed. At compilation time, the dynamic linker takes the object code of a file, then the address where the function is available in memory. Since functions are only included when they are called in a program, the file size is reduced.

To build a shared library (Linux only), you can use these commands :

gcc -g -fPIC -Wall -Werror -Wextra -pedantic *.c -shared -o libfiles.so
  • -fPIC :

This flag stands for the generation of “position-independent code”, a requirements for shared libraries. Since there is no way to find out where the code in the shared library will be stored, this flag allows the code to be located at any desired virtual location adresse at runtime.

  • -shared :

The option -shared will create a dynamic or shared library (shared libraries have the prefix lib and the suffix .so [for shared object]).

The last step is to add a library environmental variable so the program could know where to look:

export LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH

To use a dynamic library (Linux only) :

gcc -g -wall -o prog prog.c libfiles.so

References:

--

--

Elmustapha Abourar

Software Engineer Student @Holberton School & Pro Dancers Choreographer DeeJay / Beat Maker