A glimpse into the difference between static and shared(dynamic) libraries

Why using libraries in general

To execute your program, you’d need to compile the program with all of the source files.

  • example gcc prog.c mod1.c mod2.c mod3.c

the work around of this to group all of the files into a object library. The two types are static libraries and shared(dynamic) libraries.

How do they work and their difference

There is a difference between shared libraries and static libraries

  • When a program is built by linking a static library, a copy of all the files within the static library is included in the executable process. So that every program with have a copy of the complete library for it’s own references. As a result this can make your executables fairly big.
  • When you use a dynamic library the library is stored in memory. So the executable code will have a reference to the library, so that when a other programs need access to the object modules, they will reference the object library. The dynamic library will look for the symbolic reference to the dynamic library.

Pros and cons of dynamic and static libraries

  • Static libraries can place a set of commonly used object files into a single library file without having to recompile the source file. They are also faster as the complied code has direct access to the object modules without having to search through the same way the dynamic library does.
  • Dynamic libraries don’t waste the disk space like static library and there is only one copy of the library. If different programs use the same modules they can share reference to the same object module. Dynamic libraries are also also easier to update as you can change object modules without needing to relink the

How to create them (Linux only)

  • To create a static library with all the c files in your current directory
gcc -Wall -Werror -Wextra -pedantic -c *.c; 
ar -rc liball.a *.o;
rm *.o
  • to create a shared library with all the c file in your current directory
gcc -g -c -fPIC -Wall *.c
gcc -g -o *.o liball.so

How to use them (Linux only)

  • to use a static library liball.a with your file prog.c.
gcc -g -c prog.c
gcc -g -o prog prog.o liball.a
  • to use a dynamic library, liball.so with your prog.c
gcc -g -wall -o prog prog.c liball.so