Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Static Libraries in C

Introduction

Static libraries are a collection of object files that are linked into the program during the linking phase of compilation. Static libraries are also known as archive libraries and have a .a extension on Unix-like systems and .lib on Windows. In this tutorial, we will explore how to create and use static libraries in C.

Creating Object Files

To create a static library, we first need to compile source code files into object files. Consider two source files: math_functions.c and string_functions.c.

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

int subtract(int a, int b) {
    return a - b;
}
                
string_functions.c
#include <string.h>

int string_length(char *str) {
    return strlen(str);
}

void string_copy(char *dest, char *src) {
    strcpy(dest, src);
}
                

Compile these files into object files:

gcc -c math_functions.c string_functions.c

This will produce math_functions.o and string_functions.o.

Creating the Static Library

Next, we use the ar (archiver) command to create a static library from the object files:

ar rcs libmystaticlib.a math_functions.o string_functions.o

This command creates a static library named libmystaticlib.a.

Linking the Static Library

To use the static library in a program, we need to link it during the compilation of our main program. Consider the following main program:

main.c
#include <stdio.h>

int add(int a, int b);
int subtract(int a, int b);
int string_length(char *str);
void string_copy(char *dest, char *src);

int main() {
    printf("Addition: %d\n", add(3, 4));
    printf("Subtraction: %d\n", subtract(7, 2));

    char str[] = "Hello";
    char copy[6];
    string_copy(copy, str);
    printf("String copy: %s\n", copy);
    printf("String length: %d\n", string_length(str));

    return 0;
}
                

Compile and link the main program with the static library:

gcc -o myprogram main.c -L. -lmystaticlib

The -L. option tells the compiler to look in the current directory for libraries, and -lmystaticlib links the static library.

Running the Program

Finally, run the compiled program:

./myprogram
Addition: 7
Subtraction: 5
String copy: Hello
String length: 5
                

The program should produce the correct output, demonstrating that the static library was successfully created and linked.

Conclusion

In this tutorial, we covered the basics of creating and using static libraries in C. We learned how to compile source files to object files, create a static library using the ar command, and link the static library to a main program. Static libraries are useful for reusing code and can significantly reduce the size of your source code by modularizing functionalities.