Skip to main content
Compilation Toolchain
Compilation Toolchain
IOT
1h30

Libraries: Static and Dynamic

Libraries

Principle

  • Reusable package (without providing source)
  • Contains binary file and associated header files

Examples

  • libc: printf / scanf / malloc…
  • libm: sqrt / pow / floor…

These libraries are now linked automatically in any C program.

How To Use Libraries

  • Libraries follow the pattern libNAME.yy
  • To link a library, add -lNAME to gcc
  • Default search paths are /usr/lib/ and /usr/local/lib/
  • If your libraries are located elsewhere, specify the location with -Lpath

Static vs Dynamic

Libraries can be static or dynamic:

TypeWindowsUnixDarwin
Static.lib.a.a
Dynamic.dll.so.dylib

Static Libraries

Embedded in the program

  • Pros: No dependencies
  • Cons: Executable size, if the library is modified the program needs to be rebuilt

Dynamic Libraries

Linking done at execution

  • Pros: Lighter program, no rebuild if library is modified, library is present at most 1 time in RAM
  • Cons: Starting delay, dependencies

Dependencies

How to be sure that a program with dynamic libs can run on other computers?

A program will not run if a library is not available or older than required.

Versions

A dynamic lib follows the pattern: libNAME.M.m.p.EXT

  • M = major version (backward compatibility not guaranteed)
  • m = minor (backward compatibility, bugs removed)
  • p = patch (bugs removed, no incompatibility)

Know Your Libraries

$ ls -l /usr/local/lib/libgpg*
lrwxr-xr-x libgpg-error.0.dylib -> ../Cellar/libgpg-error/1.39/lib/libgpg-error.0.dylib
lrwxr-xr-x libgpg-error.a -> ../Cellar/libgpg-error/1.39/lib/libgpg-error.a
lrwxr-xr-x libgpg-error.dylib -> ../Cellar/libgpg-error/1.39/lib/libgpg-error.dylib
...

When you link a library:

gcc test.c -lgpgme

By default the one with the biggest M.m.p is chosen.

Required Dynamic Libraries

$ ldd /usr/bin/gcc
    linux-vdso.so.1 (0x00007fff967eb000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fce65c6d000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fce65aac000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fce65e00000)

Static Library Build

To create libZZZZ.a:

$ ar rcs libZZZZ.a xxxx.o yyyy.o
$ ar -t libXXXX.a
xxxx.o
yyyy.o

Dynamic Library Build

To create libtest.so:

$ gcc [options] -fPIC -c xxxx.c yyyy.c
$ gcc -shared -Wl,-soname,libtest.so.1 -o libtest.so.1.0 *.o