Static and Dynamic Libraries and CMake
In questa pagina 8
Why libraries
A library is pre-existing, already compiled code ready for use: generic functionality (linked lists, binary trees holding any data) or specific functionality (interface to a database server). Larger projects contain several libraries, some reusable in later projects or separated for organization. For a reusable or logically distinct set of functions, build a library so you do not copy the source into every project and recompile it each time: once written and tested it is reused safely. Modular programming and header files: see the earlier notes on compilation and linking of this course.
From source to running program
- Preprocessor: handles every directive, i.e. lines starting with
#(#define,#include). - Compilation (proper): turns each preprocessed
.cfile into an.o(object) file. - Linking: object files and libraries are linked into the final program. With static libraries the actual library code is placed in the program; with shared libraries only a reference to the library is placed inside. The program can then be launched from the shell and is handed to the loader.
- Loading: at program start, the program is scanned for references to shared libraries; the references found are resolved and the libraries are mapped into the program.
Static library (Linux/gcc)
A collection of object files linked directly into the application at compile time. The code becomes part of the executable; no external dependency at run time.
Steps: write the sources; compile to .o; bundle with ar into a .a; write a program that uses it; compile/link; run.
Library sources:
// lib_utils.c
#include "lib_utils.h"
int addition(int a, int b) {
return a + b;
}
int subtraction(int a, int b) {
return a - b;
}// lib_utils.h
#ifndef LIB_UTILS_H
#define LIB_UTILS_H
int addition(int a, int b);
int subtraction(int a, int b);
#endifThe #ifndef ... #define ... #endif wrapper is the include guard: the header is processed only once even if included several times.
Build the library:
gcc -c lib_utils.c
ar rcs libutils.a lib_utils.oar option |
Meaning |
|---|---|
r |
insert files into the archive (replace if existing) |
c |
create the archive if it does not exist |
s |
add an index to the archive (faster linking) |
t |
list the contents of the archive |
x |
extract files from the archive |
d |
delete files from the archive |
q |
quick append (does not check duplicates) |
v |
verbose output |
Program using the library:
// main.c
#include <stdio.h>
#include "lib_utils.h"
int main() {
int a = 5, b = 3;
printf("Add: %d\n", addition(a, b));
printf("Subtract: %d\n", subtraction(a, b));
return 0;
}gcc main.c -L. -lutils -o program
./program-L. = look for libraries in the current directory; -lutils = link libutils (the lib prefix and the extension are dropped in the option). Convention: static libraries are named lib<name>.a.
Dynamic (shared) library (Linux/gcc)
Linked at run time: smaller executables, and several programs share the same library.
Steps: same sources; compile as position-independent code; bundle into a .so; compile/link the program against it; set the library path; run.
gcc -c -fPIC lib_utils.c
gcc -shared -o libutils.so lib_utils.o
gcc main.c -L. -lutils -o program
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
./program-fPIC: position-independent code.-shared: produce a shared library.LD_LIBRARY_PATHtells the loader where to find the.soat run time (here the current directory is added); without it the program starts with an error because the library is not found.ldd ./programshows the libraries linked to an executable.
Static vs dynamic
| Feature | Static library (.a) |
Dynamic library (.so) |
|---|---|---|
| Linking | at compile time | at run time |
| Executable size | larger (library code included) | smaller (code not included) |
| Portability | self-contained executable | needs the library available at run time |
| Updates | requires recompilation | library can be updated independently |
Libraries in Microsoft Visual Studio
On Windows a static library is .lib (linked at compile time, code included in the executable); a dynamic library is .dll (linked at run time) and comes with an import library .lib.
Static library (.lib):
- File > New > Project > C++ > Library > Static Library (.lib); name it (e.g.
StaticMathLibrary). - Add the header and the source:
// MathUtils.h
#pragma once
#ifndef MATH_UTILS_H
#define MATH_UTILS_H
int addition(int a, int b);
int subtraction(int a, int b);
#endif// MathUtils.c
#include "pch.h"
#include "MathUtils.h"
int addition(int a, int b) {
return a + b;
}
int subtraction(int a, int b) {
return a - b;
}- Build (Ctrl+Shift+B or Build > Build Solution): a
.libappears in theDebugorReleasefolder. - In a new Console Application project: add
MathUtils.h; Properties > Linker > Input > Additional Dependencies: the.libname; Properties > VC++ Directories > Library Directories: the path to the.lib; then write the program (samemainas above,#include "MathUtils.h") and build and run.
Dynamic library (.dll): same procedure with the template C++ > Library > Dynamic-link Library (.dll) (e.g. DynamicMathLibrary). The header must export/import the functions:
// MathUtils.h
#pragma once
#ifndef MATH_UTILS_H
#define MATH_UTILS_H
#ifdef MATHUTILS_EXPORTS
#define MATHUTILS_API __declspec(dllexport)
#else
#define MATHUTILS_API __declspec(dllimport)
#endif
MATHUTILS_API int addition(int a, int b);
MATHUTILS_API int subtraction(int a, int b);
#endifMathUtils.c is the same as above. Building produces the .dll and an import .lib. The client project links the import .lib (same Linker/VC++ Directories settings) and the .dll must be in the executable's directory or in a system path.
| Feature (Visual Studio) | Static (.lib) |
Dynamic (.dll) |
|---|---|---|
| Linking | compile time | run time |
| Extension | .lib |
.dll (plus an import .lib) |
| Executable size | larger | smaller |
| Usage | self-contained | needs the .dll at run time |
CMake
A cross-platform build system: the same sources are built on different operating systems. Workflow:
- write
CMakeLists.txt(sources, targets, dependencies); cmakegenerates platform-specific build files (Makefiles on Linux, Visual Studio projects on Windows);- build with the generated files.
Directory structure of the example:
project/
├── src/
│ ├── main.c
│ └── helper.c
├── include/
│ └── helper.h
└── CMakeLists.txtThe listing on the slide shows helper.c/helper.h, but the example code and the CMakeLists.txt use utils.c/utils.h: the names must match the files actually used.
// main.c
#include <stdio.h>
#include "utils.h"
int main() {
printf("Result: %d\n", addition(5, 3));
return 0;
}// utils.c
#include "utils.h"
int addition(int a, int b) {
return(a + b);
}// utils.h
#ifndef UTILS_H
#define UTILS_H
int addition(int a, int b);
#endif(The slide prints UTILS _H with a stray space in the #define: the guard name must be written without it.)
cmake_minimum_required(VERSION 3.10)
# Project name and version
project(CrossPlatformExecutable VERSION 1.0)
# Specify the C standard
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED True)
# Include directories
include_directories(include)
# Add the executable
add_executable(my_program src/main.c src/utils.c)| Command | Role |
|---|---|
cmake_minimum_required |
minimum CMake version, so the following commands run with a compatible CMake |
project() |
sets the project name (required in every project); can also set language and version |
add_executable() |
creates an executable from the listed sources |
set() |
sets a normal, cache or environment variable |
CMAKE_C_STANDARD |
C standard whose features are requested |
CMAKE_C_STANDARD_REQUIRED |
boolean: whether that standard is a requirement |
include_directories() |
adds directories where the compiler looks for headers (relative paths are relative to the current source directory) |
Reference given on the slides: the CMake tutorial at cmake.org (https://cmake.org/cmake/help/latest/guide/tutorial/index.html).
Generating build files
Linux / macOS (from the project directory):
mkdir build
cd build
cmake ..
makeThe executable my_program appears in build/.
If CMake is not installed, download the sources from cmake.org/files and build:
tar xzf cmake-3.31.3.tar.gz
cd cmake-3.31.3
./configure --help
./configure --prefix=/opt/cmake
make
make install
/opt/cmake/bin/cmake -version(--prefix=/opt/cmake installs in /opt/cmake; the last command checks the installation.)
Windows (Visual Studio): from a Command Prompt or Developer Command Prompt:
mkdir build
cd build
cmake .. -G "Visual Studio 17 2022"then open the generated .sln in Visual Studio and build to get my_program.exe.
Cross-compiling
Windows from Linux with MinGW (install mingw-w64):
mkdir build
cd build
cmake .. -DCMAKE_SYSTEM_NAME=Windows -DCMAKE_C_COMPILER=x86_64-w64-mingw32-gcc
makeProduces my_program.exe.
macOS from Linux (cross-compilation toolchain such as osxcross, configure the macOS SDK):
mkdir build
cd build
cmake .. -DCMAKE_SYSTEM_NAME=Darwin -DCMAKE_OSX_SYSROOT=/path/to/macOS/SDK
makeOS-specific settings and install
Conditional checks in CMakeLists.txt:
if(WIN32)
message(STATUS "Configuring for Windows")
add_definitions(-DPLATFORM_WINDOWS)
elseif(APPLE)
message(STATUS "Configuring for macOS")
add_definitions(-DPLATFORM_MACOS)
elseif(UNIX)
message(STATUS "Configuring for Linux/Unix")
add_definitions(-DPLATFORM_LINUX)
endif()Installation rule (install() generates installation rules; DESTINATION is the target directory, preferably a relative path):
install(TARGETS my_program DESTINATION bin)cmake --install build --prefix /path/to/installTesting on different systems: Docker, virtual machines, CI/CD platforms (GitHub Actions, GitLab CI, Azure Pipelines) can build on several platforms automatically. In short, CMake hides the differences by generating the right build files for each OS.
Using a third-party library: OpenSSL
OpenSSL: toolkit for cryptographic protocols (SSL/TLS) and algorithms. Steps on Linux:
- Get the source from openssl-library.org/source, extract it.
- Configure with
./config(usually does the right thing). - Compile with
make: it creates the libraries and the headers.
Program computing the SHA256 hash of a string:
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
void print_hash(unsigned char *hash, int length) {
for (int i = 0; i < length; i++) {
printf("%02x", hash[i]);
}
printf("\n");
}
int main() {
const char *input = "Hello, OpenSSL!";
unsigned char hash[SHA256_DIGEST_LENGTH];
// Compute SHA256 hash
SHA256((unsigned char *)input, strlen(input), hash);
printf("Input: %s\n", input);
printf("SHA256 Hash: ");
print_hash(hash, SHA256_DIGEST_LENGTH);
return 0;
}Compile by linking libssl and libcrypto; -I gives the header folder, -L the library folder:
gcc hash_example.c -Iopenssl_include_folder -Lopenssl_libraries_folder -o hash_example -lssl -lcrypto
./hash_exampleOutput on the slide: Input: Hello, OpenSSL! and SHA256 Hash: 63ee7f365450f9586dbb31c9b59db63817797e04ea1014dd5a8ac6615d44fac1. The folder holding the OpenSSL libraries must be in LD_LIBRARY_PATH:
LD_LIBRARY_PATH=/path/to/openssl-3.0.14:$LD_LIBRARY_PATH(Path adapted: the slide uses a personal installation folder.)
AES encryption and decryption of one 16-byte block:
#include <openssl/aes.h>
#include <stdio.h>
#include <string.h>
void print_data(const char *label, const unsigned char *data, int len) {
printf("%s: ", label);
for (int i = 0; i < len; i++) {
printf("%02x", data[i]);
}
printf("\n");
}
int main() {
unsigned char key[AES_BLOCK_SIZE] = "mysecretkey12345"; // 16-byte key
unsigned char input[AES_BLOCK_SIZE] = "plaintextblock"; // 16-byte plaintext
unsigned char encrypted[AES_BLOCK_SIZE];
unsigned char decrypted[AES_BLOCK_SIZE];
AES_KEY encryptKey, decryptKey;
// Set encryption and decryption keys
AES_set_encrypt_key(key, 128, &encryptKey);
AES_set_decrypt_key(key, 128, &decryptKey);
// Encrypt
AES_encrypt(input, encrypted, &encryptKey);
print_data("Encrypted", encrypted, AES_BLOCK_SIZE);
// Decrypt
AES_decrypt(encrypted, decrypted, &decryptKey);
print_data("Decrypted", decrypted, AES_BLOCK_SIZE);
return 0;
}Compile with the same -I, -L, -lssl -lcrypto options. Output on the slide: Encrypted: 688f323f61bea6031efdd4060154ed69, Decrypted: 706c61696e74657874626c6f636b0000 (the ASCII of plaintextblock plus two zero bytes of padding), decrypted ASCII plaintextblock.
For secure network communication OpenSSL has SSL/TLS APIs (client overview from the slides):
SSL_CTX *ctx = SSL_CTX_new(TLS_client_method()); // 1. set up the SSL context
SSL *ssl = SSL_new(ctx); // 2. create the SSL object
SSL_set_fd(ssl, socket_fd); // attach it to the socket
SSL_connect(ssl); // TLS handshake
SSL_write(ssl, buffer, length); // 3. read/write
SSL_read(ssl, buffer, length);
SSL_free(ssl); // 4. clean up
SSL_CTX_free(ctx);The socket itself comes from Socket ProgrammingA socket is a communication endpoint identified like a file descriptor; a TCP server runs socket, setsockopt, bind, listen, accept, read/write, close, while the client runs socket, connect, read/write, close.Socket Programming →. Pointers, memory and structs used by the library API: Puntatori in CUn puntatore contiene un indirizzo di memoria; operatori & e *, NULL, puntatori come parametri per modificare variabili del chiamante, aritmetica dei puntatori, legame tra array e puntatori, const, puntatori a puntatori.Puntatori in C →, Gestione della memoria in CSegmenti di memoria di un processo (codice, dati statici, stack, heap); durata delle variabili; allocazione dinamica con malloc, calloc, realloc e free; errori classici: memory leak, dangling pointer, double free, buffer overflow; strumenti di controllo.Gestione della memoria in C →.
Versione ripasso
- Why libraries: compiled code written and tested once, reused in many projects without copying the source. Build chain: preprocessor (lines starting with
#) -> compilation (each.cbecomes an.o) -> linking (static: the library code is placed in the program; shared: only a reference) -> loading (at start the references to shared libraries are resolved and the libraries are mapped). - Header with include guard, processed once even when included twice:
#ifndef LIB_UTILS_H
#define LIB_UTILS_H
int addition(int a, int b);
int subtraction(int a, int b);
#endif- Static library (
.a, Linux):gcc -c lib_utils.c,ar rcs libutils.a lib_utils.o, thengcc main.c -L. -lutils -o program. The code becomes part of the executable.aroptions:rinsert or replace,ccreate,sindex,tlist,xextract,ddelete,qquick append,vverbose. Convention:lib<name>.a, linked as-l<name>(thelibprefix is dropped). - Dynamic library (
.so):gcc -c -fPIC lib_utils.c,gcc -shared -o libutils.so lib_utils.o, link as above, then add the current folder toLD_LIBRARY_PATHbefore./program.-fPICgives position-independent code,-sharedmakes the library;ldd ./programlists the libraries used. - Static versus dynamic: link time versus run time; static gives a bigger, self-contained executable and needs recompilation to update; dynamic gives a smaller executable, several programs can share it, it can be updated on its own, but must be present at run time.
- Typical "library not found" at run time means
LD_LIBRARY_PATHis missing the folder. Other typical errors: forgetting-fPIC, typing-llibutilsinstead of-lutils. - Visual Studio: a static library gives a
.lib(code in the executable). A dynamic one gives a.dllplus an import.lib. The DLL header uses__declspec(dllexport)when building (MATHUTILS_EXPORTSdefined) and__declspec(dllimport)for clients, through a macroMATHUTILS_API. The client links the import.lib(Linker > Input, VC++ Directories) and the.dllmust be next to the executable or on the system path. - CMake: a cross-platform build system. You write
CMakeLists.txt,cmakegenerates the platform build files (Makefiles or Visual Studio projects), then you build them. Minimal file:
cmake_minimum_required(VERSION 3.10)
project(CrossPlatformExecutable VERSION 1.0)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED True)
include_directories(include)
add_executable(my_program src/main.c src/utils.c)- CMake commands:
cmake_minimum_required(minimum version),project()(required, sets the name),add_executable()(sources to executable),set()(variables),CMAKE_C_STANDARDandCMAKE_C_STANDARD_REQUIRED(C standard),include_directories()(where headers are searched; relative paths are relative to the current source directory). - Build on Linux:
mkdir build,cd build,cmake ..,make; the executable appears inbuild/. Windows:cmake .. -G "Visual Studio 17 2022", then build the generated.sln. - Cross-compiling:
cmake .. -DCMAKE_SYSTEM_NAME=Windows -DCMAKE_C_COMPILER=x86_64-w64-mingw32-gcc(MinGW from Linux) producesmy_program.exe; for macOS use-DCMAKE_SYSTEM_NAME=Darwinand a macOS SDK through-DCMAKE_OSX_SYSROOT. - OS checks in
CMakeLists.txt:if(WIN32),elseif(APPLE),elseif(UNIX), each withadd_definitions(-DPLATFORM_...). Installation:install(TARGETS my_program DESTINATION bin), thencmake --install build --prefix /path/to/install. - OpenSSL as third-party library: include the headers with
-I, the libraries with-L, link with-lssl -lcrypto, and put the library folder inLD_LIBRARY_PATH. Example:SHA256((unsigned char *)input, strlen(input), hash);withSHA256_DIGEST_LENGTHbytes printed as%02x. AES:AES_set_encrypt_key(key, 128, &encryptKey),AES_encrypt(input, encrypted, &encryptKey), with a 16-byte block. - TLS client flow:
SSL_CTX_new(TLS_client_method()),SSL_new(ctx),SSL_set_fd(ssl, fd),SSL_connect(ssl)(handshake),SSL_write/SSL_read, thenSSL_freeandSSL_CTX_free. The socket comes from Socket ProgrammingA socket is a communication endpoint identified like a file descriptor; a TCP server runs socket, setsockopt, bind, listen, accept, read/write, close, while the client runs socket, connect, read/write, close.Socket Programming →. - Typical errors: mismatch between file names and
CMakeLists.txt; header without include guard; stray space in#define UTILS _H; a.dllnot found at run time.