![]() |
VOOZH | about |
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.
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.
Follow the given steps to create a static libary:
Create the header file that declares the functions to be used from the library. For example, mylib.h.
mylib.h
Create the source file that implements the functions declared in the header file. For example, mylib.c.
mylib.c
Compile the source file into an object file (.o or .obj). For GCC, use the following command
gcc -c mylib.c -o mylib.oUse 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
Output
Hello, World!But to compile it with GCC, we need to pass some additional arguments:
gcc main.c -L. -lmylib -o myprogram