Useful Information about C Static Libraries

--

In this article we will review the basics of C static libraries. We will try to answer some general questions, which are: Why do we use libraries ? How do they work ? How to create them ? And how to use them ? These questions are our start pointers of all of the article. Let’s get into it.

Before anything, I think it should be more than appropriate to define what is a static library. A static library is a file which contains a variety of different object files or items that are used to link your code with functions and variables so that it can execute something. Linking your program with a static library makes it faster than linking a program whose objects are in a separated disk.

Why do we use libraries ? And how do they work ?

First of all, we use them in order to bring them to life, without them your code would not have sense. Without them, your code could not be executed, therefore it wouldn’t work at all. Libraries are tools provided by the compilers so that your code could be read, so taking this into account, libraries helps you out translating your code to an understandable language for your machine. They work be receiving a code containing functions and different types of variables, and analyzing if they exist in the library and what characteristics they have, when identified, it returns what it was asked.

How to create and use them ?

First of all you have to compile your c programs with the following command:

gcc -c *.c

There is a program used to create static libraries called “ar”, which is for “archiver”; according to the manual, this program creates, modifies and extracts from archives. We use the following command to create it:

$ ar rc holberton.a

The r flag means that whatever old object that are in the library will be replaced with the newest ones created. On the other hand, the c flag means that the archive will be created.

When you have done this you must create an index for the library using the “ranlib” command. This program makes a header in the library with the symbols of the object file contents. You should run this command after:

ranlib holberton.a

After creating the static library to have to compile it with the library, so it can be linked with it and the program can run properly. You also have to take into mind the main file in order to test it. Run this command:

gcc main.c -L. -lholberton.a -o exe

The -L flag tells the linker that libraries could be found in the working directory. The -l flag searches the specified library, so that it could be taken in mind. The -o option defines the name of the executable, which in this case is “exe”. After this simply execute your executable file.

./exe

I hope this works for all of the people who are interested in this topic. Thanks for reading and hopefully appreciate the information I tried to explain.

--

--