Creating a Static C Library on Linux

Say you wrote some C functions and you want to package them to be used later by other programs.. what would be the best way to accomplish this? Creating a library of course! A library in C is a collection of functions and declarations which is made available to be used by other programs. There are two different kinds of libraries, Static and Dynamic. Let’s take a look at Static libraries.

Let’s start out with a few C functions that accomplish various tasks.

First thing you want to do is to compile these C files using gcc, the command “gcc -c *.c” assembles the source files, but does not link them. The output of this command is in the form of an object file for each C file. By default, the object file name will be the source file name with a ‘.o’ instead of a ‘.c’ at the end.

The next command we need to use to create a Static library is the “ar” command. “ar” can create, modify, or extract archives. We should add the “-rc” options, the r stands for “Insert the files member… into archive (with replacement). Any previously existing members are deleted if their names match those being added.” , and the c stands for “Create the archive. The specified archive is always created if it did not exist, when you request an update. But a warning is issued unless you specify in advance that you expect to create it, by using this modifier.”

As we can see bellow, after we write the “ar -rc lib_my_functions.a *.o”, the system created a library files called lib_my_functions.a that includes all the files in the folder that end with a “.o”.

We can confirm what’s inside the library with the “ar -t” command, as you can see bellow, all the “.o” files are included in the lib_my_functions.a library file.

After that we should run the “ranlib lib_my_functions.a” command which “generates an index to the contents of an archive and stores it in the archive.” A library with such an index speeds up linking to the library and
 allows routines in the library to call each other without regard to
 their placement in the archive.

That’s it! We’re done. We have created a Static library from our custom functions. But now how are we able to use it? Say we have a little function that prints a statement using our _puts function.

If we use gcc to try to compile it we get an error.

This is because we never included the static library we created in the gcc command. The correct way to do it is this:

the “-L.” option looks in current directory for library files, and the “-l” attached to the library name (minus the “lib”) includes the _my_functions library in the linking process. So now the function _puts inside main.c can be linked to its function definition in the lib_my_functions.a library.

So now when we run the output file “main”, we get this!

Like what you read? Give Christian Agha a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.