Creating and Using Libraries in C Language
Introduction
Libraries in C are collections of precompiled code that can be reused in various programs. They help in organizing code, improving reusability, and maintaining modularity. In this tutorial, we will learn how to create and use both static and dynamic libraries in C.
Creating a Static Library
A static library is a collection of object files that are linked into the program during the linking phase of compilation.
Step 1: Write the Library Code
Create a header file my_math.h
and a source file my_math.c
with the following content:
#ifndef MY_MATH_H #define MY_MATH_H int add(int a, int b); int subtract(int a, int b); #endif
#include "my_math.h" int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; }
Step 2: Compile the Library Code
Compile the source file into an object file:
Step 3: Create the Static Library
Use the ar
command to create a static library:
The library file libmymath.a
is now created.
Step 4: Use the Static Library in a Program
Create a main program file main.c
:
#include#include "my_math.h" int main() { int a = 10, b = 5; printf("Add: %d\n", add(a, b)); printf("Subtract: %d\n", subtract(a, b)); return 0; }
Compile the main program with the static library:
Run the program:
Subtract: 5
Creating a Dynamic Library
A dynamic library is a collection of routines that are loaded into memory and linked dynamically at runtime.
Step 1: Write the Library Code
The code for the dynamic library is the same as for the static library. Use the same my_math.h
and my_math.c
files.
Step 2: Compile the Library Code
Compile the source file into a position-independent object file:
Step 3: Create the Dynamic Library
Use the gcc
command to create a dynamic library:
The library file libmymath.so
is now created.
Step 4: Use the Dynamic Library in a Program
Use the same main.c
file as before. Compile the main program with the dynamic library:
Set the LD_LIBRARY_PATH
to include the current directory:
Run the program:
Subtract: 5
Conclusion
In this tutorial, we have learned how to create and use both static and dynamic libraries in C. Libraries help in reusing code efficiently and maintaining modularity in your programs. By following the steps outlined above, you can create your own libraries and use them in various projects.