C static libraries

Jacer Dabbabi
3 min readMar 1, 2020

What are static libraries ?

A library is a package of code that is meant to be reused by many programs . Typically, a C library comes in two pieces:

  1. A header file that defines the functionality the library is exposing (offering) to the programs using it.
  2. A precompiled binary that contains the implementation of that functionality pre-compiled into machine language.

Why use libraries ?

One advantage of static libraries is that you only have to distribute the executable in order for users to run your program. Because the library becomes part of your program, this ensures that the right version of the library is always used with your program. Also, because static libraries become part of your program, you can use them just like functionality you’ve written for your own program.

How do they work ?

A static library consists of routines that are compiled and linked directly into your program. When you compile a program that uses a static library, all the functionality of the static library that your program uses becomes part of your executable.

How to create them ?

First we need to compile our C files into object code. We can do that using:

Next, we need to create our static library and add files to it. We can do this with the command:

After we’ve added everything to our standard library, there’s a need to index the library. Indexing the library can be done by running the command ranlib libexample.a. Indexing the library is important as it speeds up the linking process when the library is called.

How to use them ?

To use this static library we would create a program -lets call it my_program.c that used functions from the library we just created. To use the library functions, we need to tell the compiler where to look. We could run the command:

--

--