C Static Libraries — explained.

Caroline
2 min readMar 1, 2021

A static library is a group of pre-compiled functions, called object files, packaged together in what is called a library. Their purpose is to avoid programmers having to write the same code over and over. As they can just simply call to the functions in the library. A static library is stored locally, at the end of compilation the linker copies its code into the object file. You can find more about the compilation process here: https://cmdelcarmen.medium.com/the-steps-of-compilation-using-the-gcc-compiler-3a3de56f9c06

How to create you first static library (in Linux):

  1. Open your your terminal and create a “.c” file. For example: add.c.
  2. Inside, write a function that adds two integers.
  3. Create a header file with the prototype to your add.c file inside.
  4. Compile your add.c file using the command:
gcc -c add.c

This command will create a machine language file called add.o.

5. Create you static library now by using the command:

ar rc libfirttime.a add.o

ar” is the program used to create the file. “rc” are options, c tells it to create the library if it already doesn’t exists, while r tells it to replace older object files with new mans. Man ar to learn more.

6. You can use this command to see what files are inside your static library:

ar -t libfirstime.a

Whenever you find yourself writing the same lines of code over and over, and there is no dynamic library function available to you, feel free to create your own static C library. For a cleaner and faster coding process.

--

--

Caroline
0 Followers

Holberton School Programming Student