Practical Examples
Example 1: Math Library Compilation
Source Code
#include <stdio.h>
#include <math.h>
int main() {
double number = 16.0;
printf("Square root: %.2f\n", sqrt(number));
return 0;
}
Compilation Process
gcc -o math_example math_example.c -lm
./math_example
Example 2: Creating Custom Static Library
Library Source Code
// utils.c
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
Compilation Steps
## Compile object files
gcc -c utils.c -o utils.o
## Create static library
ar rcs libutils.a utils.o
## Compile main program
gcc -o calculator main.c -L. -lutils
Example 3: Dynamic Library Integration
Library Implementation
// custom_lib.c
#include <stdio.h>
void print_message(const char* msg) {
printf("Custom Library: %s\n", msg);
}
Compilation Workflow
## Create dynamic library
gcc -shared -o libcustom.so -fPIC custom_lib.c
## Install library
sudo cp libcustom.so /usr/local/lib
sudo ldconfig
## Compile main program
gcc -o program main.c -lcustom
Library Usage Scenarios
Scenario |
Library Type |
Use Case |
Mathematical Calculations |
Static |
Numerical computations |
Networking |
Dynamic |
Socket programming |
Graphics |
Mixed |
Rendering engines |
Dependency Management
graph TD
A[Project] --> B[External Libraries]
B --> C[Math Library]
B --> D[Graphics Library]
B --> E[Network Library]
Advanced Compilation Flags
gcc -O2 program.c -o optimized_program
Debugging Support
gcc -g program.c -o debug_program
LabEx Recommended Workflow
- Identify library requirements
- Install necessary development packages
- Write modular code
- Link libraries efficiently
- Test and validate
Common Pitfalls to Avoid
- Mismatched library versions
- Incorrect linking order
- Missing header files
- Incompatible compilation flags
graph LR
A[Library Selection] --> B[Static]
A --> C[Dynamic]
B --> D[Faster Execution]
C --> E[Smaller Executable]
Best Practices
- Use pkg-config for library management
- Keep libraries updated
- Handle library dependencies carefully
- Use version control for library configurations
By mastering these practical examples, you'll develop robust C programs with efficient library integration strategies.