2. The Problem
At some time you might have to load a library (and use its
functions) at runtime; this happens most often when you are
writing some kind of plug-in or module architecture for your
program.
In the C language, loading a library is very simple (calling
dlopen, dlsym and
dlclose is enough), with C++ this is a bit
more complicated. The difficulties of loading a C++ library
dynamically are partially due to name
mangling, and partially due to the fact that the
dlopen API was written with C in mind, thus
not offering a suitable way to load classes.
Before explaining how to load libraries in C++, let's better
analyze the problem by looking at name mangling in more
detail. I recommend you read the explanation of name mangling,
even if you're not interested in it because it will help you
understanding why problems occur and how to solve them.
2.1. Name Mangling
In every C++ program (or library, or object file), all
non-static functions are represented in the binary file as
symbols. These symbols are special text
strings that uniquely identify a function in the program,
library, or object file.
In C, the symbol name is the same as the function name:
the symbol of strcpy will be
strcpy, and so on. This is
possible because in C no two non-static functions can have the
same name.
Because C++ allows overloading (different functions with
the same name but different arguments) and has many features C
does not — like classes, member functions, exception
specifications — it is not possible to simply use the
function name as the symbol name. To solve that, C++ uses
so-called name mangling, which transforms
the function name and all the necessary information (like the
number and size of the arguments) into some weird-looking
string which only the compiler knows about. The mangled name
of foo might look like
foo@4%6^, for example. Or it
might not even contain the word "foo".
One of the problems with name mangling is that the C++
standard (currently [ISO14882]) does not
define how names have to be mangled; thus every compiler
mangles names in its own way. Some compilers even change their
name mangling algorithm between different versions (notably
g++ 2.x and 3.x). Even if you worked out how your particular
compiler mangles names (and would thus be able to load
functions via dlsym), this would most
probably work with your compiler only, and might already be
broken with the next version.
2.2. Classes
Another problem with the dlopen API
is the fact that it only supports loading
functions. But in C++ a library often
exposes a class which you would like to use in your
program. Obviously, to use that class you need to create an
instance of it, but that cannot be easily done.