Entry
how to call function in .so files
Aug 12th, 2004 06:16
Hans Holmberg, Jay Nayegandhi, jaya prakash,
Suppose you want to use something in library /somelibdir/libFoo.so.
When you build your program, you will need to add a -L option to tell
the linker which directory to look for the library, and a -l option for
which library:
cc -L/somelibdir myprogram.c -lFoo
At run time, libFoo must be visible to the linker. Different Unices
have different ways of making this happen. The dynamic linker will
have a default search path that includes directories such as /lib
and /usr/lib. Other directories may be included through use of the
environment variable LD_LIBRARY_PATH. Look at the man page for your
dynamic linker(usually 'ld.so') for details.
---
Note by Hans Holmberg:
In most modern unixes you can use dlopen() and dlsym() to load a library
dynamicly on the fly without the need to use ld on your binary.
Here's the example that you will find in the linux manpages:
#include <stdio.h>
#include <dlfcn.h>
int main(int argc, char **argv) {
void *handle;
double (*cosine)(double);
char *error;
handle = dlopen ("libm.so", RTLD_LAZY);
if (!handle) {
fprintf (stderr, "%s\n", dlerror());
exit(1);
}
cosine = dlsym(handle, "cos");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "%s\n", error);
exit(1);
}
printf ("%f\n", (*cosine)(2.0));
dlclose(handle);
return 0;
}
Remember, in some instances dlsym() will return 0 or NULL if the symbol
has that value, allthough it will also return 0 or NULL when the symbol
doesn't exist. To make sure the returned value is a correct one ALWAYS
call dlerror() afterwards.
It's also a good idea to make sure libraries are loaded in the correct
dependency order if you open more than one library.
There's a good writeup on using libraries by David Wheeler at
http://www.dwheeler.com/program-library/Program-Library-HOWTO/index.html