Static Libraries in C

Jhonatan Jauja
2 min readMar 8, 2021
Credits: https://iconos8.es/icon/40670/c-programaci%C3%B3n

A Library is a set of functions. Usually a developer can create a new library, to reuse all its typical functions to be called from some other program. It’s like a program, only it doesn’t have a main () function.

Kind of libraries

Static Libraries. They are linked when compiling, they remain “inside” the final executable. In Linux they have the extension .a.

Dynamic Libraries. They are linked when executing, the operating system must find them when executing the program.

Advantages and Disadvantages of Static Libraries

  • Static libraries resist vulnerability because it lives inside the executable file.
  • The speed at run-time occurs faster because its object code (binary) is in the executable file. Thus, calls made to the functions get executed quicker.
  • Changes made to the files and program require relinking and recompilation.
  • File size is much larger.
Credits: https://medium.com/@StueyGK/what-is-c-static-library-fb895b911db1

How to create static libraries in C

  1. Create a C file that contains functions in your library.
  2. Create a header file for the library, for example you can create
    $ vim mylib.h
  3. Compile library files.
    $ gcc -c mylib.c -o mylib.o
  4. Create static library. This step is to bundle multiple object files in one static library (see ar for details). The output of this step is static library.
    $ ar rc mylib.a mylib.o
    The ar” stands for archive and it is used to create the static library. All the files ending in .o will be added to the mylib.a library and they are the object files in this case.
    The
    -rc flag will do two things: replace and create a new library if it does not exist already.
  5. The next step is indexing, to do that, we type:
    $ranlib
    mylib.a
  6. Now our static library is ready to use. At this point we could just copy mylib.a somewhere else to use it. For demo purposes, let us keep the library in the current directory.

How to use static libraries in C

Finally to use the static library, type the following command:

gcc main.c -L -l<filename>

The -L flag accesses the linker so the libraries can be found in the given directory. Also, it also searches for other locations where the compiler looks for system libraries.

--

--