What are libraries and why use libraries in c ?

Types of libraries in C:

Static libraries

Shared or dynamic libraries

How static libraries work

What is the difference between them

Creating A Static “C” Library

ar rc libutil.a util_file.o

This command creates a static library named ‘libutil.a’ and puts copie of the object file “util_file.o” .If the library file already exists, it has the object file added to it, or replaced, if they are newer than those inside the library. The 'c' flag tells ar to create the library if it doesn't already exist. The 'r' flag tells it to replace older object file in the library, with the new object file.

After an archive is created, or modified, there is a 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.The command used to create or update the index is called 'ranlib', and is invoked as follows:

ranlib libutil.a

Note: when an archive file’s index generation date (stored inside the archive file) is older than the file’s last modification date (stored in the file system), a compiler trying to use this library will complain its index is out of date, and abort. There are two ways to overcome the problem:

  1. Use 'ranlib' to re-generate the index.
  2. When copying the archive file to another location, use 'cp -p', instead of only 'cp'. The '-p' flag tells 'cp' to keep all attributes of the file, including its access permissions, owner (if "cp" is invoked by a superuser) and its last modification date. This will cause the compiler to think the index inside the file is still updated. This method is useful for makefiles that need to copy the library to another directory for some reason.

How to use libraries in C

gcc main.o -L. -lutil -o prog

This will create a program using object file "main.o", and any symbols it requires from the "util" static library. Note that we omitted the "lib" prefix and the ".a" suffix when mentioning the library on the link command. The linker attaches these parts back to the name of the library to create a name of a file to look for. Note also the usage of the '-L' flag - this flag tells the linker that libraries might be found in the given directory ('.', refering to the current directory), in addition to the standard locations where the compiler looks for system libraries.

“Programming is a race between developers, trying to build bigger and better idiot-proof programs, and the universe, trying to produce bigger and better idiots. For now the Universe is winning”
- Rich Cook

I hope this article has helped you understand about C libraries and their great importance in programming in C and C++. Grettings!)