Differences between static and dynamic libraries

A library is a file containing several object files, that can be used as a single entity in a linking phase of a program.

Why use libraries?

How do they work? And What are the differences between static and dynamic libraries?

Static Library

Dynamic library

To read more about to the advantages and disadvantages of each one. You can go to the final of the blog :)

How to create them(Linux)?

Static Library:

gcc -Wall -pedantic -Werror -Wextra -c *.car -rc libholbertonschool.a *.o
ar -t libholbertonschool.a
/* Run */
ranlib libholbertonschool.a
gcc main.c -L. -lholbertonschool -o alpha
./alpha

After an archive is created, or modified, there is a need to index it. This index is later used by the compiler to speed up symbol-lookup inside the library, and to make sure that the order of the symbols in the library won’t matter during compilation. The command used to create or update the index is called 'ranlib', and is invoked as follows:

ranlib libholbertonschool.a

Dynamic Library:

gcc -Wall -fPIC -c *.c

This command will take your “.c” files and return object code files ending in “.o”. After it you need to the next step to create a dynamic library like this:

gcc -shared -o liball.so *.o

How to use them(Linux)?

gcc main.c -L. -lholbertonschool -o alpha

Dinamyc library

gcc -Wall -pedantic -Werror -Wextra -L. 0-main.c -lholberton -o len

Also before compile is important to add the localization of your library with the environmental variable to know where to find them:

export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH

What are the advantages and drawbacks of each of them?

Static linking:

Disadvantages: the size of a.out is larger than a executable file created with a dynamic linking.

Dynamic linking:

  • The size of a.out is smaller.
  • You can run several programs which the same library functions because you called it from the memory and it is more efficiently
  • We don’t need to compile the source files again if we modify any library functions

Disadvantages:

  • The executable files are not self-sufficient. It means that will always depend on the version of DLL. For example, if we change the functions in the library, maybe in the future the executable file will not compile!

Examples:

Static library

Dynamic Library

You can create and run this bash or can write in the terminal the next image:

executable bash to create a library with all file C typle and then use the file *.o to create de DLL

Then you call like in this example:

you compile your main and create your executable file with the dynamic library, then you ran your executable problem, according to the image , in this case is “./len”

I hope that you like the article and thanks for reading :)

Software engineer in progress