See Your “C” Library?’

Felicia
2 min readJun 5, 2017

--

A Static Library (of a sort)

Ever wonder where your favorite printf statement in a C program is implemented? Well, the object code for this function (as well as others) is in the standard C library, libc.so, and prototyped in the stdio.h header file. If you run ldd /bin/ls, you can view your shared libraries. Here is an example on a Linux machine.

My Shared Libraries

Why Use Libraries?

By keeping common functions in a central location, a library, it means your other programs can have access to this library as well. Another advantage is that linking to a central set of libraries instead of individual files improves linking time during program compilation.

How they work

You do not have to explicitly link to your library. The Linker automatically looks in libraries for functions that it does not find elsewhere. When the include file is in brackets, the Preprocessor in the compiler searches in paths specified via the -I flag. Then it searches the standard include paths and uses the -v flag to test on your system.

How to create them?

Creating a static library is surprisingly easy and fast. First, centralize your working source files into a directory and compile the code into *.o files.

Generate *.o Object Files

Create the library archive with the ar command. Use the -r option to replace any member function with the new object code. Use the -c option to create a new library if it does not exist. The convention is to name your library with a “lib” prefix and a “.a” extension.

ar -rc lib[YOURLIBNAME].a *.o

You should have a file named, lib[YOURLIBNAME].a in your directory.

Then, to verify every member function was included in the library, use the -t option to view the functions in a table.

ar -t lib[YOURLIBNAME].a

Next, use the ranlib function to generate an index to the archive/library to speed up Linking.

ranlib lib[YOURLIBNAME].a

How to use them?

In your main.c program, call a function defined in a library, say, “_putchar(‘H’);” and compile the program and run it.

gcc main.c -L. -l[YOURLIBNAME] -o main

Simple, isn’t it?

--

--