Practical Implementation
Creating a Custom Library
Step-by-Step Library Development
graph LR
A[Write Functions] --> B[Compile Object Files]
B --> C[Create Library]
C --> D[Link with Main Program]
Example Project Structure
project/
│
├── include/
│ └── mathutils.h
├── src/
│ ├── mathutils.c
│ └── main.c
└── Makefile
Implementing Static Library
#ifndef MATHUTILS_H
#define MATHUTILS_H
int add(int a, int b);
int subtract(int a, int b);
#endif
Implementation File (mathutils.c)
#include "mathutils.h"
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
Compilation Process
Creating Static Library
## Compile object files
gcc -c -I./include src/mathutils.c -o mathutils.o
## Create static library
ar rcs libmathutils.a mathutils.o
Dynamic Library Implementation
Shared Library Compilation
## Compile with position independent code
gcc -c -fPIC -I./include src/mathutils.c -o mathutils.o
## Create shared library
gcc -shared -o libmathutils.so mathutils.o
Linking Strategies
Linking Type |
Command Example |
Pros |
Cons |
Static Linking |
gcc main.c -L. -lmathutils.a -o program |
Standalone executable |
Larger file size |
Dynamic Linking |
gcc main.c -L. -lmathutils -o program |
Smaller executable |
Runtime dependency |
Main Program Example (main.c)
#include <stdio.h>
#include "mathutils.h"
int main() {
int result = add(5, 3);
printf("5 + 3 = %d\n", result);
return 0;
}
Running the Program
Set Library Path
## Add current directory to library path
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
## Compile and run
gcc main.c -L. -lmathutils -o program
./program
Debugging Library Linking
Useful Commands
## Check library dependencies
ldd program
## Verify symbol resolution
nm -D libmathutils.so
LabEx Best Practices
- Use consistent naming conventions
- Manage library versions carefully
- Document library interfaces
- Handle error conditions
Common Pitfalls
- Incorrect library paths
- Version mismatches
- Symbol visibility issues
- Unresolved dependencies
Advanced Techniques
Using pkg-config
## Simplify library compilation
gcc $(pkg-config --cflags --libs libexample) main.c -o program
- Minimize library dependencies
- Use lightweight libraries
- Consider static linking for performance-critical applications