==================
== beto's notes ==
==================

C Programming

Libraries

A static library is included inside the binary file, while the dynamic library is linked to the binary, which means it’s not included within it. Dynamic libraries can be compiled independently of the executable.

Dynamically linked binaries depend on the libraries available in the system.

1# Find the library locally
2whereis library-name
3
4# Helps inspecting the symbols. (`-D` for dynamic libraries).
5nm -D library-location

Static Libraries

Creating a static library requires first compiling, without linking, and creating an archive.

1gcc -Wall -Wextra -pedantic -std=c99 -c file.c
2ar -cvr libfile.a file.o
3
4# Compile everything
5gcc -Wall -Wextra -pendantic -std=c99 main.c libfile.a -o main
6# Remove symbols
7strip main

To compile a statically linked binary we’ll need to install it system-wide with similar steps to installing dynamic libraries, but using the archive format (.a). With the difference that the static library doesn’t require the executable bit.

1gcc -Wall -Wextra -pedantic -std=c99 -static main.c -lfile -o main

Dynamic Libraries

A dynamic library needs to be compiled as Position-Independent Code (PIC), so it can be executed at different addresses in different processes.

Aftwards, a shared object (.so) is required to be able to load at runtime. The real name, must follow the lib[lib-name].so.[major-version].?[minor-version]

1# Generate Position-Independent Code(PIC)
2gcc -Wall -Wextra -pedantic -fPIC -c file.c
3gcc -shared -Wl,-soname,libfile.so -o libfile.so.1 file.o
4# `-L` includes the path required to find `-lfile` since it's not globally installed
5gcc -L${PWD} -lfile main.c -o main
6
7# Check .so symbols
8readelf --symbols

Dynamic libraries can be loaded from custom paths setting the LD_LIBRARY_PATH environment variable.

1export LD_LIBRARY_PATH=${PWD}:${LD_LIBRARY_PATH}

We can check which libraries are dynamically linked to our executable by running ldd [executable-name].

Installing Dynamic Libraries

Libraries installed by the user should be located in /usr/local/lib.

1sudo install -o root -g root -m 755 libfile.so.1 /usr/local/lib/libfile.so.1
2# To use `#include <file.h>` instead of `#include "file.h"`
3sudo install -o root -g root -m 644 file.h /usr/local/include/file.h
4sudo ldconfig # This creates a symbolic link libfile.so