|
17.1 Dynamic Modules
In order to dynamically load some code into your executable, that code
must be compiled in some special but architecture dependent fashion.
Depending on the compiler you use and the platform you are compiling
for, there are different conventions you must observe in the code for
the module, and for the particular combination of compiler options you
need to select if the resulting objects are to be suitable for use in
a dynamic module. For the rest of this chapter I will concentrate on
the conventions used when compiling dynamic modules with GCC on
GNU/Linux, which although peculiar to this particular combination
of compiler and host architecture, are typical of the sorts of
conventions you would need to observe on other architectures or with
a different compiler.
With GCC on GNU/Linux, you must compile each of the source
files with `-fPIC'(38), the resulting
objects must be linked into a loadable module with gcc 's
`-shared' option:
|
$ gcc -fPIC -c foo.c
$ gcc -fPIC -c bar.c
$ gcc -shared -o baz.so foo.o bar.o
|
This is pretty similar to how you might go about linking a shared
library, except that the `baz.so' module will never be linked with
a `-lbaz' option, so the `lib' prefix isn't necessary. In
fact, it would probably be confusing if you used the prefix.
Similarly, there is no constraint to use any particular filename
suffix, but it is sensible to use the target's native shared library
suffix (GNU/Linux uses `.so') to make it obvious that the
compiled file is some sort of shared object, and not a normal
executable.
Apart from that, the only difference between a shared library built for
linking at compile-time and a dynamic module built for loading at
run-time is that the module must provide known entry points for
the main executable to call. That is, when writing code destined for a
dynamic module, you must provide functions or variables with known names
and semantics that the main executable can use to access the
functionality of the module. This is different to the function
and variable names in a regular library, which are already known when
you write the client code, since the libraries are always written
before the code that uses them; a runtime module loading system
must, by definition, be able to cope with modules that are written
after the code that uses those modules.
|