Static libraries C

Julian Torres
2 min readJul 6, 2020

Why use libraries?

Free wills are files (not always external) that allow us to carry out different tasks without having to worry about how they are done but simply understand how to use them. The C-freeways allow us to make our programs more modular and reusable, also making it easier to create programs with quite complex functionalities in a few lines of code.

How to create and use them:

In order to create a static library using GCC, we need to compile our library code into an object file, we achieve this using the -c flag with GCC

$ gcc -c * .c

All .c files in the current directory have been converted to object files, now with the ar(keeps filegroups as one compressed) command we will create our library

$ ar -rc library.a * .o

Once our file is created, we must index it what we will do with the ranlib command. this command creates an index of the contents of the library and stores them.

$ ranlib library.a

Now that we have our library created we can list the objects of this as follows

$ ar -t library.a

Another way to list this would be with the nm command, which would list the files with the objects it contains.

$ nm library.a

Now using the following GCC indicators we can make use of our library

$ gcc main.c -L. -lrary -o main

  • -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.

--

--