$ cc -Aa testlib.c -o testlib -ldld $ testlib

libfoo loaded 1.0in = 2.54cm 1.0gal = 3.79l 1.0oz = 28.35g libfoo unloaded

Example: A Common Initializer for Multiple Libraries

Rather than have a unique initializer for each library, libraries can have one initializer that calls the actual initialization code for each library. To use this technique, each library declares and references the same initializer (for example, _INITIALIZER), which calls the appropriate initialization code for each library. This is easily done by defining load and unload functions in each library. When _INITIALIZER is called, it uses shl_findsym to find and call the load or unload function (depending on the value of the loading flag). The following example shows the source for an _INITIALIZER function:

C Source for _INITIALIZER (file init.c) #include <dl.h>

/*

*Global initializer used by shared libraries that have

*registered it:

*/

void _INITIALIZER(shl_t hand, int loading)

{

void (*load_unload)();

if (loading)

shl_findsym(&hand, "load", TYPE_PROCEDURE, (void *) &load_unload); else

shl_findsym(&hand, "unload", TYPE_PROCEDURE, (void *) &load_unload);

(*load_unload) ();

/* call the function */

}

The following two source files show shared libraries that have registered _INITIALIZER.

C Source for libunits.c #include <stdio.h> #include <dl.h>

void load()

/* called after libunits.so loaded */

{

 

printf("libunits.so loaded\n");

}

 

void unload()

/* called after libunits.so unloaded */

{

 

printf("libunits.so unloaded\n");

}

 

extern void _INITIALIZER();

 

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);

 

146 Shared Library Management Routines