C Static libraries.

A C library is a set of named functions.

Static libraries permit users to link to programs without having to recompile its code, saving recompilation time.

A static library is simply a unix archive made form the relocatable object files (*.o). Such a library is usually linked together with other object files to form an executable object file.

To create a static library, we need to specify to the compiler, which is GCC in our case, that we want to compile all library codes (*.c) into object files (*.o) without linking. To do that we are going to use the command below.

$ gcc -c -Wall -Werror -Wextra *.c

Flags description:

The -c flag compile and assemble, but do no link.

-Wall, -Werro and -Wextra: These aren’t necessary but they are recommended to generate better code.

For example: let us take two c files, 01_function.c and 02_function.c

The picture below shows the output generated after using the command.

ubuntu@ip-172-31-63-244:~/holbertonschool$ ls01_function.c 02_function.cubuntu@ip-172-31-63-244:~/holbertonschool$ gcc -Wall -pedantic -Werror -Wextra -c *.cubuntu@ip-172-31-63-244:~/holbertonschool$ ls01_function.c 01_function.o 02_function.c 02_function.o

To create a static library or to add additional object files to an existing static library, we have to use the GNU ar (archiver) program. We can use a command like this:

ubuntu@ip-172-31-63-244:~/holbertonschool$ ar -rc lib_name.a *.o

This command creates a static library named “lib_name.a” and puts copies of the object files “01_fucntion.o” and “02_function.o” in it. The ‘c’ flag tells ar to create the library if it doesn’t already exist. The ‘r’ flag tells it to insert object files or replace existing object files in the library, with the new object files.

Once you’ve created a static library, you’ll want to use it. You can use a static library by invoking it as part of the compilation and linking process when creating a program executable.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store