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
#output</PRE>

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,libXXX.so.N -o libXXX.so.N.M *.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 libXXX.so.N.M.P -Wl,-soname,libXXX.so.N -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

1)
  gcc -fPIC -O2 -I. -c source1.c -o source1.so
  gcc -fPIC -O2 -i. -c source2.c -o source2.so
2)
  ld -x -r source1.so
  mv a.out source1.so
  ld -x -r source2.so
  mv a.out source2.so
3)
  gcc -shared -Wl,-soname,libsource.so.1 -o libsource.so.1.0 source*.o
4)
  mv libsource.so.1.0 /usr/lib
  ln -s /usr/lib/libsource.so.1.0 /usr/lib/libsource.so.1