What is a static library:

How a Static library Works:

How to create a Static Library:

$ gcc -c *.c

Here in the above command , all the .c extension files( C files) in the current working directory have been converted in to their respective object files. Once we have object file(s), we use the GNU ar command to create our final library/archive

The archiver, also known simply as ar, is a Unix utility that maintains groups of files as a single archive file.

$ ar -rc libholberton.a *.o

This tells ar to create an archive (option c) and to insert the objects, replacing older files where needed (option r) .

Whenever files are added to a library, including the initial creation of the library , the library needs to be indexed, which is done with the command ranlib. ranlib makes a header in the library with the symbols of the object file contents.This helps the compiler to quickly reference symbols. A large library may have thousands of symbols meaning an index can significantly speed up finding references.

$ ranlib libholberton.a

We can also see the symbols in our library, using the command nm, which lists each symbol’s symbol value, symbol type, and symbol name from object files.

nm lib_test.a

How to use a Static Library:

  • -l<libraryname without lib prefix and extension>
  • -L : specifies the path to the library .We can use -L. inorder to point to the current directory and -L/home/tmp to point to the /home/tmp directory.
gcc main.c -L. -lholberton -o main

Now run the executable program ‘main’

$./main

The two main disadvantages are..

  • If the library code is updated (say, to fix a bug) you have to recompile your program into a new executable.
  • Every program in the system that uses that library contains a copy in its executable. This is very inefficient (and a pain if you find a bug and have to recompile, as per point one).

It is in these cases that we find Dynamic or Shared libraries better. Shared libraries are an elegant way around the problems posed by a static library. A shared library is a library that is loaded dynamically at runtime for each application that requires it. But more on this in another post.