• Why use libraries
  • How they work
  • How to create them
  • How to use them

Why use libraries?

When should we use the static libraries?

How do the C static libraries work?

Taken from Megha Mohan

The library accepts only object files, that means, files that are assembled by the compiler, then all of those object files are reserved inside a file, then when we compile a program with the main function and that calls any of the functions inside the library, we can tell the compiler to compile the main file and link with the program file the library that has all the functions we need.

How to create a C static library?

ar rc libutil.a util_file.o util_net.o util_math.o

This command creates a static library named 'libutil.a' and puts copies of the object files "util_file.o", "util_net.o" and "util_math.o" in it. The 'c' flag tells ar to create the library if it doesn't already exist. The 'r' flag tells it to replace older object files in the library, with the new object files.

After an archive is created, or modified, we need to index it. This index is later used by the compiler to speed up symbol-lookup inside the library, and to make sure that the order of the symbols in the library won’t matter during compilation. To create or update the index we use 'ranlib', just like this:

ranlib libutil.a

How to use the static library?


gcc main.c -lutil -L. -o main

Here we put the name ‘util’ with neither the prefix ‘lib’ nor the suffix ‘.a’, the linker puts that name in the back of the library, so for next ocations the linker will recognize it with that name, also we defined the path or the directory where the library is, that’s what the ‘.’ after ‘-L’ means, and what it is saying yo the program is: “That library is in this directory”. Otherwise you should specify the path where the library is folded.

I'm a Full-Stack Developing student