C static library

When a project tends to be larger, we need to find a way to improve it in terms of efficiency and readability, this is when we should think in libraries.

Unix systems ( and almost all new systems) allow us to create 2 kinds of libraries, static libraries and dynamic (or shared) libraries.

We are going to focus on static libraries, which are just collections of object files that are linked into a program during the linking phase of compilation.

To use a library that is not already linked to your program, you need to include your header file in your C file and tell the compiler to link the object files related to the library to your executable file.

The resulting executable file will contain machine code for all the functions defined in our c file plus any library function that is called by creating and using your library code.

To create your static library you need to do the following:

  • Place all your functions in separate C files (functionX.c) and compile them in .o object files with the following command: gcc -c functioname.c (do this for every function or do it at once with gcc -c *.c — all functions must be in the present working directory).
  • The basic tool to create a static library is a program called ‘ar’ for ‘archiver’. Now we know that static libraries are actually archive files. In order to create the static library, we can use a command-line like this: ar rc liball.a *.o
  • At this point, we have successfully created our library called liball.a that contains all the object files that we have created in the first step in the present working directory.

Using a static library is even easier than creating one. Just need to add the library’s name to the list of object file names given to the linker, using the flag ‘-L.’ this way: ‘cc main.o -L. -lall -o programname’. Note that we omitted the ‘lib’ part and the .a extension in our library name.

And that all, now it’s up to you to get used to this useful tool to manage better our coding experience. Good luck!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store