Posted by: Catalin | October 22, 2008

How to create a static library using C

Before you start doing your library you should be clear about three concepts:

  • type of linkage (internal, external, and no linkage)
  • type of objects (internal, and external)
  • scope (per function, per program, …)

, and good explanations you find at this location => Linkage <= .

Ok, let’s assume that you already have a libheader.h, and a libdeclared.c files, where in the first one you have all your definitions, and in the second your program declarations.

Compiling and  assembling your library is simple and performed with gcc, obviously! The proper command to do it is:

gcc -g -c -Wall libdeclared.c # it will produce a libdeclared.o file

Now you have an object file and must create an archive with your lib:

ar rcs libdeclared.a libdeclared.o

Good, now you have a static library and you wish to see what objects does your lib has:

nm -s libdeclared.a

So, using your library is quite simple and looks like this:

gcc -o <your_binary_file> <your_file.c> -L<directory_of_your_lib> <yourlib.a>

Enjoy now!


Leave a response

Your response:

Categories