Tag Archives: Unix

Create static and shared libraries in Unix

Static Library
Lets first look at how static library can be created and used :

(a) Compile print.c to get an object file :
gcc -c print.c -o print.o

(b) Create a static library (archive) of the object file :
ar rcs libprint.a print.o

According to *nix norms, static library’s name should start with ‘lib’ and have ‘.a’ extension. ar is a unix tool to create, modify and extract from archives.

(c) Now compile main.c and link it statically to the library.
gcc -static main.c -L. -lprint -o statically_linked

$ ./statically_linked
hello world!

Shared Library
One of the most important things to note while creating shared libraries is the object files should be compiled with -fPIC option (position-independent code).

(a) gcc -fPIC -c print.c -o print.o

(b) gcc -shared -o libprint.so print.o

(c) gcc main.c -o dynamically_linked -L. -lprint

$ LD_LIBRARY_PATH=. ./dynamically_linked
hello world!

Note: Detailed explanation of the above used gcc switches can be found in gcc manual pages.