C static libraries

Laura Andrea Álvarez
3 min readJul 4, 2020
C static libraries
  • Why use libraries

In a similar way as the real life, a library is a set of books, but in the programming´s field a library is a set of functions, variables or routines.

It is very common coding several times the same function such a part of process of compilation of a program. that process is unuseful, because we can most time code the whole program, even we can destroy our code. In those cases libraries could be useful because they allow call the functions many times without code the code again again and it could reduce the space in memory.

  • How they work

Static library is purely a collection of .o files, put together in an archive that's something like a zip file (with no compression). When you use it for linking, the linker will search the library for .o files that provide any of the missing symbols in the main program, and pull in those .o files for linking, as if they had been included on the command line like .o files in your main program. This process is applied recursively, so if any of the .o files pulled in from the library have unresolved symbols, the library is searched again for other .o files that provide the definitions.

  • How to create them

1. Identify the functions that you want to keep inside the library: remember that functions must be writing in a file .c extension and it have to contain the protptype o the function

2. If the funcions are located in diferents directories is necesary move (copy)all of them at the same directory.

This example show how you can copy of the files.c to the final directory
Directory destiny

3. Create a header file(.h) that contain the prototypes included inside the each functions. This file also must contain the directives #ifndef #define at the top and #endif at the bottom , so the header file is only defined once instead of each time it is called.

4. Compile all of the .c files (*.c) in the counterpart object (.o)

5. Finally, create the library with the files.o using the option-r to ensure that if the library (.a) file already exists, it will be replaced. The command option -c should be used so that if the file doesn’t exist, it will be created.

The basic tool used to create static libraries is a program called 'ar', for 'archiver'. This program can be used to create static libraries (which are actually archive files), modify object files in the static library, list the names of object files in the library, and so on. In order to create a static library, we can use a command like this:

6. You can visualize the content:

  • How to use them

When the library is created, you can reference for to run a program. For example:

--

--

Laura Andrea Álvarez

Futura ingeniera en inteligencia de negocios. Ingeniera administradora y prospectivista