206 Chapter 6
Shared Library Management Routines
Initializers for Shared Libraries
C Source for libfoo.sl
#include <stdio.h>
#include <dl.h>
/*
* This is the local initializer that is called when the libfoo.sl
* is loaded and unloaded:
*/
void init_foo(shl_t hndl, int loading)
{
if (loading)
printf(“libfoo loaded\n”);
else
printf(“libfoo unloaded\n”);
}
float in_to_cm(float in) /* convert inches to
centimeters */
{
return (in * 2.54);
}
float gal_to_l(float gal) /* convert gallons to litres
*/
{
return (gal * 3.79);
}
float oz_to_g(float oz) /* convert ounces to grams */
{
return (oz * 28.35);
}
You can use the +I linker option to register a routine as an initializer.
Here are the commands to create libfoo.sl and to register init_foo
as the initializer:
$ cc -Aa -c +z libfoo.c
$ ld -b -o libfoo.sl +I init_foo libfoo.o
To use this technique with multiple libraries, each library should have a
unique initializer name. The following example program loads and
unloads libfoo.sl.
C Source for testlib
#include <stdio.h>
#include <dl.h>
main()
{
float (*in_to_cm)(float), (*gal_to_l)(float), (*oz_to_g)(float);
shl_t hndl_foo;
/*
* Load libfoo.sl and find the required symbols:
*/
if ((hndl_foo = shl_load(“libfoo.sl”,
BIND_IMMEDIATE, 0)) == NULL)
perror(“shl_load: error loading libfoo.sl”), exit(1);