Building Shared Libraries

Creating a Shared Library

To make an archive library, you use the archiver, of course (:-).
ar rc libXXX.a *.o
ranlib libXXX.a

However, if you are using ELF, you can easily make shared libraries, so each binary you link against your library doesn't keep it's own copy of all the code - resulting in smaller binaries. This shouldn't be used if you are distributing binaries, and people won't have a copy of the library on their computer. In any case, to make a shared lib:

gcc -shared -Wl,-soname, -o *.o

where N is the major version, and M is the minor version. By convention, minor versions are compatible, but just bug fixes or whatever, while major versions are not compatible with each other.

Converting Static to Dynamic Library

If you already have a static library, you can turn it into a dynamic one by doing:

gcc -shared -o -Wl,-soname, -Wl,--whole-archive, libXXX.a,--no-whole-archive

Make sure though, that your objectfiles (and in this case, the members of the static library) have been compiled with -fPIC.

Building From Scratch

On FreeBSD, I am able to do

  gcc -fPIC -O2 -I. -c source1.c -o
  gcc -fPIC -O2 -i. -c source2.c -o
  ld -x -r
  mv a.out
  ld -x -r
  mv a.out
  gcc -shared -Wl,-soname, -o source*.o
  mv /usr/lib
  ln -s /usr/lib/ /usr/lib/