![]() |
VOOZH | about |
Libraries are a collection of code that can be used by other programs. They promote code reuse and modularity. In C, we can create our own libraries. In this article, we will learn how to create a library in C.
In C, there are multiple methods using which we can create a library.:
In this article, we will look at the static libraries. Before C++11, copying objects was the only way to transfer data, which could be slow for large objects. Move semantics allows transferring ownership of resources without copying.
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.
Create the source files for your library. For example, mylib.c and mylib.h.
mylib.h
Compile our source files into object files (.o or .obj).
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.oSTEP 5. Use the Static Library:
Link the static library to our program when compiling it.
gcc main.c -L. -lmylib -o myprogramA shared library is a collection of object files that are linked dynamically at runtime by the operating system.
Use the same source files as in the static library example.
Compile your source files into position-independent object files.
gcc -c -fPIC mylib.c -o mylib.oUse the gcc command to create the shared library (.so file).
gcc -shared -o libmylib.so mylib.oLink the shared library to your program when compiling it.
gcc main.c -L. -lmylib -o myprogramEnsure the shared library is in our library path or use the LD_LIBRARY_PATH environment variable to specify the path.
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:../myprogramBy following these steps, you can create both static and shared libraries in C.