Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

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:

my_math.h
#ifndef MY_MATH_H
#define MY_MATH_H

int add(int a, int b);
int subtract(int a, int b);

#endif
                
my_math.c
#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:

gcc -c my_math.c -o my_math.o

Step 3: Create the Static Library

Use the ar command to create a static library:

ar rcs libmymath.a my_math.o

The library file libmymath.a is now created.

Step 4: Use the Static Library in a Program

Create a main program file main.c:

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:

gcc main.c -L. -lmymath -o main

Run the program:

./main
Add: 15
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:

gcc -fPIC -c my_math.c -o my_math.o

Step 3: Create the Dynamic Library

Use the gcc command to create a dynamic library:

gcc -shared -o libmymath.so my_math.o

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:

gcc main.c -L. -lmymath -o main

Set the LD_LIBRARY_PATH to include the current directory:

export LD_LIBRARY_PATH=.

Run the program:

./main
Add: 15
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.