Finally (much less common, but still possible), dynamic linking allows users to select at runtime
which library to execute against. It's possible to create library versions that are tuned for speed, or for
memory efficiency, or that contain extra debugging information, and to allow the user to express a
preference when execution takes place by substituting one library file for another.
Dynamic linking is "just-in-time" linking. It does mean that programs need to be able to find their
libraries at runtime. The linker accomplishes this by putting library filenames or pathnames into the
executable; and this in turn, means that libraries cannot be moved completely arbitrarily. If you linked
your program against library /usr/lib/libthread.so, you cannot move the library to a
different directory unless you specified it to the linker. Otherwise, the program will fail at runtime
when it calls a function in the library, with an error message like:
ld.so.1: main: fatal: libthread.so: can't open file: errno=2
This is also an issue when you are executing on a different machine than the one on which you
compiled. The execution machine must have all the libraries that you linked with, and must have them
in the directories where you told the linker they would be. For the standard system libraries, this isn't a
problem.
The main reason for using shared libraries is to get the benefit of the ABI—freeing your software from
the need to recompile with each new release of a library or OS. As a side benefit, there are also overall
system performance advantages.
Anyone can create a static or dynamic library. You simply compile some code without a main routine,
and process the resulting .o files with the correct utility—"ar" for static libraries, or "ld" for dynamic
libraries.
Software Dogma
Only Use Dynamic Linking!
Dynamic linking is now the default on computers running System V release 4 UNIX, and it
should always be used. Static linking is now functionally obsolete, and should be allowed to
rest in peace.
The major risk you run with static linking is that future versions of the operating system will
be incompatible with the system libraries bound in with your executable. If your application
was statically linked on OS version N and you try to run it on version N+1, it may run, or it
may fail with a core dump or a less obvious error.
There is no guarantee that an earlier version of the system libraries will execute correctly on
a later version of the system. Indeed, it is usually safer to assume the opposite. However, if
an application is dynamically linked on version N of the system, it will correctly pick up the
version N+1 libraries when run on version N+1 of the system. In contrast, statically linked