Libraries in C: static or dynamic?

Photo by Evgeni Tcherkasski on Unsplash

What is a library in C?

When you write a program, chances are you may need to print something to the screen. How would you do it? Would you write a printf function from scratch or use the one available in the <stdio.h> library?

Why choose one over the other?

Remember one of the coding exercises for beginner, the one that requires to enter a name, then prints out “Hello name”? It’s certainly over simplifying but, to a certain extent, the idea is the same: when you hard-code a name, it’s static, and when you can modify the output message without having to re-compile the program, it’s dynamic.

Static library
Dynamic (or shared) library
Benchmark

How to create a Static library?

Please consult my post about for further information.

How to create a Dynamic / Shared library?

There are four main steps to build a dynamic library. The first step is the same as for the building process of a Static library.

  • -fPIC: since different programs may use the same library, and each load it into a different memory in address, we need that all calls will use relative addresses, and not absolute addresses.
  • -o: name the executable file liball.so
ldd len 
linux-vdso.so.1 => (0x00007fff5d1d2000)
libholberton.so => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f74c6bb9000)
/lib64/ld-linux-x86-64.so.2 (0x0000556be5b82000)
$ export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
ldd len
linux-vdso.so.1 => (0x00007fff41ae9000)
libholberton.so => ./libholberton.so (0x00007fd4bf2d9000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fd4beef6000)
/lib64/ld-linux-x86-64.so.2 (0x0000557566402000)

How to use a static or dynamic library?

We use the same method as for the static library to include the dynamic library in a program.

gcc -L. *.c -lname -o out
  • The -lname flag has a unique structure; -l <libraryname without lib prefix and extension>.

Software Engineer student at Holberton School. Reach me @huyxuanminh