Penguin
Note: You are viewing an old revision of this page. View the current version.

A SharedLibrary contain subroutines that can be linked to a BinaryExecutable at RunTime. This allows for sharing code between applications, which has a number of advantages:

  • It saves on disk space, since functions common to many programs don't need to exist in identical copies in each of their binaries.
  • It saves on memory for the same reason -- you only need a single copy of the SharedLibrary in memory. This also means that the memory footprint columns in ps(1) never add up correctly.
  • Fixing a bug in the shared code automatically fixes that bug for all programs that use the library, without actually having to touch these programs.
  • Likewise, performance or other improvements are automatically propagated to every program using a library.

Examining SharedLibrary dependencies on Unix

On many Unix systems, you can use the ldd(1) command to see which shared libraries a program is linked against

$ ldd /sbin/mke2fs

libext2fs.so.2 => /lib/libext2fs.so.2 (0x40023000) libcom_err.so.2 => /lib/libcom_err.so.2 (0x40037000) libe2p.so.2 => /lib/libe2p.so.2 (0x40039000) libuuid.so.1 => /lib/libuuid.so.1 (0x4003e000) libc.so.6 => /lib/libc.so.6 (0x40041000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)

Trying this on a statically linked program

$ ldd /sbin/init

not a dynamic executable

On Darwin, the corresponding program is called otool

$ otool -L /bin/zsh

/bin/zsh

/usr/lib/libncurses.5.dylib (compatibility version 5.0.0, current version 5.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 60.0.0)

Creating a SharedLibrary

Assuming the source is in the files foo.c, bar.c, baz.c, you call GCC like so
gcc -shared -Wl,-soname,libfoo.so -o libfoo.so.1.0.1 foo.c bar.c baz.c -lquux

This creates a SharedLibrary file libfoo.so.1.0.1, with shared object name ("soname") libfoo.so, dependent on libquux. To make libfoo usable, you need to put it someplace ldconfig(8) will find it, and SymLink it to libfoo.so.1 and libfoo.so.

So long as you don't change the call signature of one of the functions (or what they do, in a way that would break programs), you can just bump the minor version of the library and programs using the SharedLibrary will just work. If you do change call signatures on existing functions or change their semantics, bump the version, try to recompile the programs, and check that they work correctly once they pass.

For more information, see Ulrich Drepper's How to write shared libraries.