Expert C Programming

(Jeff_L) #1

applications have to be regenerated for every new release of the operating system to ensure
that they keep running.


Furthermore, some libraries (such as libaio.so, libdl.so, libsys.so, libresolv.so, and
librpcsvc.so) are only available in dynamic form. You are obliged to link dynamically if
your application uses any of these libraries. The best policy is to avoid problems by making
sure that all applications are dynamically linked.


Static libraries are known as archives and they are created and updated by the ar—for archive—


utility. The ar utility is misnamed; if truth in advertising applied to software, it would really be called


something like glue_files_together or even static_library_updater.


Convention dictates that static libraries have a ".a" extension on their filename. There isn't an example
of creating a static library here, because they are obsolete now, and we don't want to encourage
anyone to communicate with the spirit world.


There was an interim kind of linking used in SVR3, midway between static linking and dynamic
linking, known as "static shared libraries". Their addresses were fixed throughout their life, and thus
could be bound to without the indirection required with dynamic linking. On the other hand, they were
inflexible and required a lot of special support in the system. We won't consider them further.


A dynamically linked library is created by the link editor, ld. The conventional file extension for a


dynamic library is ".so" meaning "shared object"—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. In its simplest form, a dynamic library can be created by using the -G
option to cc, like this:


% cat tomato.c


my_lib_function() {printf("library routine called\n"); }


% cc -o libfruit.so -G tomato.c


You can then write routines that use this library, and link with it in this manner:


% cat test.c


main() { my_lib_function(); }


% cc test.c -L/home/linden -R/home/linden -lfruit


% a.out


library routine called


The -L/home/linden -R/home/linden options tell the linker in which directories to look


for libraries at linktime and at runtime, respectively.


You will probably also want to use the -K pic compiler option to produce position-independent


code for your libraries. Position-independent code means that the generated code makes sure that
every global data access is done through an extra indirection. This makes it easy to relocate the data
simply by changing one value in the table of global offsets. Similarly, every function call is generated
as a call through an indirect address in a procedure linkage table. The text can thus easily be relocated

Free download pdf