In C, we can create our own libraries that contains the code for the functions or macros that we may need very often. These libraries can be then used in our programs. In this article, we will learn how to create a custom static library and use it with GCC compiler.
What is a Static Libraries in C?
A static library is a collection of object files that are linked into the program during the linking phase of compilation, resulting in a single executable file. The static libraries code is copied to the given program before creating the executable file.
Creating Static Libary in C
Follow the given steps to create a static libary:
Step 1: Define the Header File
Create the header file that declares the functions to be used from the library. For example, mylib.h.
mylib.h
#ifndef MYLIB_H
#define MYLIB_H
void hello();
#endif // MYLIB_H
Step 2: Create the Source File for the Header
Create the source file that implements the functions declared in the header file. For example, mylib.c.
mylib.c
#include "mylib.h"
#include <stdio.h>
void hello() { printf("Hello, World!\n"); }
Step 3: Compile the Object File
Compile the source file into an object file (.o or .obj). For GCC, use the following command
gcc -c mylib.c -o mylib.oStep 4: Create the Static Library
Use the ar (archiver) command to create the static library (.a file).
ar rcs libmylib.a mylib.oAfter this, you can use the library in your program. Take the below example
Example
#include "mylib.h"
int main() {
hello();
return 0;
}
Output
Hello, World!But to compile it with GCC, we need to pass some additional arguments:
gcc main.c -L. -lmylib -o myprogram