Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Linking Libraries in C

Introduction

Linking libraries is a crucial part of programming in C. Libraries provide pre-written code that you can reuse to perform common tasks, simplifying your development process. This tutorial will guide you through the process of linking libraries in C, both statically and dynamically.

Static Linking

Static linking involves copying all the library functions used in your program into the final executable. This makes the executable larger, but it becomes self-contained and doesn't require external libraries at runtime.

To perform static linking, you typically use the ar tool to create an archive of the library code, and then link it using the gcc compiler.

Creating a Static Library

Consider two source files, add.c and sub.c:

/* add.c */
int add(int a, int b) {
    return a + b;
}

/* sub.c */
int sub(int a, int b) {
    return a - b;
}

First, compile these source files into object files:

gcc -c add.c sub.c

Next, create a static library archive named libmath.a:

ar rcs libmath.a add.o sub.o

Linking the Static Library

Now, create a main program that uses the functions in the static library:

/* main.c */
#include 

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

int main() {
    printf("3 + 4 = %d\n", add(3, 4));
    printf("7 - 2 = %d\n", sub(7, 2));
    return 0;
}

Compile and link the main program with the static library:

gcc -o main main.c -L. -lmath

Run the executable:

./main
3 + 4 = 7 7 - 2 = 5

Dynamic Linking

Dynamic linking involves linking the library at runtime rather than at compile time. This keeps the executable smaller, but the required libraries must be available at runtime.

Creating a Dynamic Library

Use the same source files, add.c and sub.c, but compile them with the -fPIC flag to produce position-independent code:

gcc -c -fPIC add.c sub.c

Create a shared library named libmath.so:

gcc -shared -o libmath.so add.o sub.o

Linking the Dynamic Library

Compile the main program, but link it with the shared library:

gcc -o main main.c -L. -lmath

Set the LD_LIBRARY_PATH to include the current directory:

export LD_LIBRARY_PATH=.

Run the executable:

./main
3 + 4 = 7 7 - 2 = 5

Conclusion

Linking libraries in C can be done either statically or dynamically. Each method has its pros and cons, and the choice depends on the specific requirements of your project. Static linking creates a self-contained executable, while dynamic linking results in smaller executables but requires the presence of the libraries at runtime. Understanding both methods will help you make informed decisions in your development process.