Library Files
Libraries are collections of precompiled methods that provide ready-to-use variables, functions, or classes. They exist as files on a computer system.
Linux supports two types of libraries: static libraries (with .a extension) and shared libraries (with .so extension). The naming convention follows lib[name].a for static libraries and lib[name].so for shared libraries.
Both library types are generated from object (.o) files, requiring compilation of source files first:
gcc -c source_file.c
Static Libraries
To create a static library:
# Generate position-independent object files
g++ -c module1.cpp module2.cpp -I ./include/
# Create static library
ar rcs libmylib.a module1.o module2.o
Key compilation flags:
-L: Specifies library directory path-l: Specifies library name (excluding lib prefix and .a suffix)
Static library distribution includes:
- Header files (.h) containing function declarations
- Library file (.a) containing binary function definitions
Shared Libraries
Creating shared libraries involves:
# Generate position-independent object files
g++ -c -fPIC module1.cpp module2.cpp -I ./include/
# Create shared library
g++ -shared module1.o module2.o -o libmylib.so
Alternative single-command approach:
g++ -fPIC -shared module1.cpp module2.cpp -o libmylib.so -I ./include/
Library Configuration
Standard installation locations:
- Headers: /usr/local/include
- Libraries: /usr/local/lib
Runtime library configuraton:
# Edit library configuration
vim /etc/ld.so.conf
# Create custom configuration
cd /etc/ld.so.conf.d/
vim custom_libs.conf
Add library paths to configuration files for runtime discovery.
Key Differences
Static libraries are copied into each executable that uses them, resulting in code duplication when multiple programs use the same library. This can lead to significant memory waste with large libraries or many dependent programs.
Shared libraries are loaded once at runtime and shared among all programs that use them, reducing memory consumption through code sharing.