C has two different types of libraries: a static library, and a shared library. Libraries are great for massive programs, since a large program would take a very long to compile and link. Having a library chops up the program into smaller chunks of source code to reduce overall compilation and linking time. This blog will be going through a static library; which one of the tools that the compiler supplies, and is just a collection of object files that are linked into the program during the linking phase of compilation. These object files are small units of source code that are related to the program.
Creating a static library: To create a static library, you first need to use the archiver:
ar rc libname.a main1.o main2.o main3.o .
ar is the archiver command, and this code has 2 flags:
r is for replacing older object files in the library with newer ones, and
c is for creating the library if it doesn’t already exist. After the flags, you give the library a name along with it’s extension
.a (in this case, it is
libname.a ). Following the name are the object files that you want to store in the library. To create these object files, you will need to run the
gcc command along with the
-c flag, and following the source code files that you want to make into an object files. So an example of this would be:
gcc -c main1.c main2.c main3.c .
After creating the archive, we need to index it. The index is used by the compiler to speed up symbol-lookup inside the library. To index, an example code would be:
ranlib libname.a . The command for indexing is
ranlib , following the library file.
How to use our indexed library: as mentioned in my previous blog about running
gcc; in the compiling process, object code and libraries are passed through the linker to create an executable file. So the flags for adding libraries into your executable is:
-L. -l . The
L tells the linker that libraries might be found in the given directory (
. here is referring to the current directory. After that, the
l is for adding the specific library name (note that “lib” and .a extension are omitted when using this flag). So the example code would be:
gcc main.c -L. -lname . This code will create an executable called
a.out (by default) that has the library
libname.a linked to it. Any functions from
libname.a are now usable in