Overview
Static libraries are collections of compiled object files that are linked into your program at compile time. They provide a way to organize and reuse code across multiple projects without needing to recompile the source files each time.What is a Static Library?
A static library is an archive of object files (.o files) created using the ar (archive) utility. In Linux, static libraries conventionally have the .a extension and are named with a lib prefix (e.g., libmy.a).
Advantages
- Fast execution: No runtime linking overhead
- Portable: Everything is contained in the executable
- Version stability: No dependency on external library versions
Disadvantages
- Larger executables: Library code is copied into each program
- Updates require recompilation: Changes to the library require relinking all programs
Creating a Static Library
Library Functions
Our static library includes common string and memory manipulation functions:main.h
Example Implementations
Build Process
Compile Source Files to Object Files
Compile each This creates object files like
.c file into an object file (.o):_strlen.o, _memset.o, _strcmp.o, etc.Create the Archive
Use the Flags explained:
ar command to create the static library:r- Replace or add files to the archivec- Create the archive if it doesn’t exist
Automated Build Script
The complete build process can be automated with a shell script:create_static_lib.sh
Using the Static Library
Compilation
To use the library in your program:-L.- Look for libraries in the current directory-lmy- Link againstlibmy.a(thelibprefix and.asuffix are implicit)
Example Program
main.c
Examining Library Contents
List Archive Contents
Display Symbol Table
Detailed Listing
Common Issues and Solutions
Undefined reference errors
Undefined reference errors
If you get undefined reference errors during linking:
- Ensure the library is in the library path (
-Lflag) - Check that you’re linking the correct library (
-lflag) - Verify the function exists in the library with
nm
Wrong order of arguments
Wrong order of arguments
The order matters when compiling with static libraries:Object files and source files should generally come before library flags.
Multiple definitions error
Multiple definitions error
This occurs when the same function is defined in multiple object files:
- Check for duplicate implementations
- Ensure each function has only one definition
- Use
nmto identify where symbols are defined
Best Practices
Naming Convention
Always prefix library names with
lib and use .a extension:libmy.alibutils.alibmath.a
Header Files
Provide header files (
.h) with function declarations for library users.Documentation
Document each function’s purpose, parameters, and return values in comments.
Testing
Test library functions thoroughly before distribution.
Related Topics
- Dynamic Libraries - Runtime linking alternative
- File I/O - Low-level file operations