Dynamic Libraries in C
Introduction
Dynamic libraries, also known as shared libraries, are a crucial component in modern software development. They allow multiple programs to share code, which reduces memory usage and disk space. Additionally, they provide a way to update libraries without recompiling the applications that use them. In this tutorial, we will explore how to create and use dynamic libraries in the C programming language.
Creating a Dynamic Library
Let's start by creating a simple dynamic library. We'll create a library that provides basic mathematical operations.
Step 1: Write the library code
Create a file named mymath.c
and add the following code:
#includeint add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; }
Step 2: Compile the library
Use the following command to compile the library:
gcc -shared -o libmymath.so -fPIC mymath.c
This command creates a shared library named libmymath.so
.
Using the Dynamic Library
Now that we have created our dynamic library, let's write a program that uses it.
Step 1: Write the main program
Create a file named main.c
and add the following code:
#includeint add(int a, int b); int subtract(int a, int b); int main() { int a = 5, b = 3; printf("Add: %d\n", add(a, b)); printf("Subtract: %d\n", subtract(a, b)); return 0; }
Step 2: Compile the main program
Use the following command to compile the main program and link it with the dynamic library:
gcc -o main main.c -L. -lmymath
This command tells the compiler to look for libraries in the current directory (-L.
) and links the libmymath.so
library (-lmymath
).
Step 3: Run the program
Before running the program, set the LD_LIBRARY_PATH
environment variable to include the current directory:
export LD_LIBRARY_PATH=.
Now run the program:
./main
Add: 8 Subtract: 2
Conclusion
In this tutorial, we have learned how to create and use dynamic libraries in C. Dynamic libraries provide a flexible and efficient way to share code between multiple programs. By using dynamic libraries, you can reduce memory usage and disk space, and update libraries without needing to recompile your applications.