How Create Static And Dynamic Libraries


01 June 2014

Programmers’ theoretical minimum: how create static or dynamic library

Create a static or dynamic library isn’t hard indeed.

It’s enough to compile your code without a main routine and process the resulting objects (.o) files with the correct utility ar for static libraries or ld for dynamic libraries:

#####square.h

double square(double);

#####square.c

double square(double num) {
  return num*num;
}

As first step is necessary to product the objects files passing -c to gcc compiler:

gcc -c square.c -o square.o

####Creating the static library Static libraries are known as archives and they are created and updated using the ar (archive) utility.

Convention dictates that static library’s name starts with lib and has an .a extension.

ar rcs libsquare.a square.o

####Creating the shared library using ld A dynamically linked library is created by the link editor ld. The conventional file extension for a dynamic library is .so meaning shared object, because every program linked against this library shares the same one copy, in contrast to static linking, in which everyone is (wastefully) given their own copy of the contents of the library.

ld -o square.so square.o

####Creating the shared library using gcc A dynamic library can also be created using gcc and passing the -shared option, like below:

gcc -shared -o square.so square.o

##Further Information

C++11

Creating a shared and static library with the gnu compiler [gcc]



blog comments powered by Disqus