A library is a collection of pre-compiled code (functions, routines, and subroutines) that programs can use to perform common tasks. Libraries are designed to be reusable, allowing multiple programs to access their functionalities without each needing its own copy of the code. This makes software more efficient, as it reduces redundancy, saves disk space, and optimizes memory usage.
Types of Libraries in Linux
Static Libraries:
These libraries are files that are linked directly into the program at compile-time, which means the functions in the library are incorporated into the executable itself.
The filename extension for static libraries is usually .a (e.g., libm.a)
Advantages: Since everything is included in the executable, the program doesn't rely on external files, which can make it more portable.
Disadvantages: The executable size is larger, as all library code is embedded, and updates require recompiling the program with the new library version.
Dynamic (Shared) Libraries:
Dynamic libraries are linked at runtime rather than compile-time, meaning they are separate from the executable and loaded into memory only when needed.
The filename extension for shared libraries is usually .so (shared object) (e.g., libm.so.6).
Advantages: Since the library is loaded at runtime, the executable size is smaller, and multiple programs can share a single instance of the library in memory.
Disadvantages: Programs depend on the presence of these libraries in the system, so removing or updating a shared library can affect all programs that use it.
How Libraries Work in Linux
Libraries provide common code that multiple applications can use, such as handling files, performing calculations, or managing network connections; when an application needs a function, it calls the functions from the library rather than including the code itself.
Example of common libraries:
Standard C Library (glibc): Contains basic functions for file handling, memory management, and other core functionalities. It's one of the most essential libraries in Linux.
Math Library (libm): Provides mathematical functions, like sin(), cos(), and sqrt().
Linking Libraries in Linux
Static Linking: The library code is embedded directly into the executable during compilation.
$ gcc -o programname programname.c .path/to/libm.a
Dynamic Linking: The Linker adds references to the library instead of the actual code and the operating system loads the library at runtime.
$ gcc -o programname programname.c -lm
Commands for working with libraries
ldd command:
Lists shared libraries required by a binary
$ ldd /bin/ls
ldconfig command:
Updates the system's library cache (useful after installing a new shared library).
$ sudo ldconfig
Libraries in Linux are integral to both system operations and application development, as they provide a structured, modular way of organizing reusable code.