shl_load Usage

Since the library was not specified at link time, the program must get the library name at run time. Here are some practical ways to do this:

Hard-code the library name into the program (the easiest method).

Get the library name from an environment variable using the getenv library routine (see getenv(3C)).

Get the library path name from the command line through argv.

Read the library name from a configuration file.

Prompt for the library path name at run time.

If successful, shl_load returns a shared library handle (of type shl_t), which uniquely identifies the library. This handle can then be passed to the shl_findsym or shl_unload routine.

Once a library is explicitly loaded, use the shl_findsym routine to get pointers to functions or data contained in the library; then call or reference them through the pointers. This is described in detail in “The shl_findsym Routine” (page 172) .

Use caution when building shared libraries with external library dependencies. Any library that contains static references to Thread Local Storage (TLS) can only be loaded implicitly at program startup. To enable dynamic loading of libraries that contain TLS, compile the library source files with the compiler option +tls=dynamic.

shl_load Example

The following example shows the source for a function named load_lib that explicitly loads a library specified by the user. The user can specify the library in the environment variable SHLPATH or as the only argument on the command line. If the user chooses neither of these methods, the function prompts for the library path name. The function then attempts to load the specified library. If successful, it returns the shared library handle, of type shl_t. If an error occurs, it displays an error message and exits. This function is used later in “The shl_findsym Routine” (page 172).

load_lib - Function to Load a Shared Library

#include

<stdio.h>

/* contains standard I/O defs

*/

 

#include

<stdlib.h>

/* contains getenv definition

 

*/

#include

<dl.h>

 

/* contains shared library type defs

*/

shl_t load_lib(int argc,

 

 

 

 

char * argv[])

/* pass argc and argv from main */

 

{

 

 

 

 

 

shl_t lib_handle;

 

/* temporarily holds library handle

*/

char

lib_path[MAXPATHLEN];

/* holds library path name

 

*/

char

*env_ptr;

 

/* points to SHLPATH variable value

*/

/*

 

 

 

 

 

*Get the shared library path name:

*/

if (argc > 1)

/* library path given on command line */

strcpy(lib_path, argv[1]);

 

else

/* get lib_path from SHLPATH variable */

{

 

env_ptr = getenv("SHLPATH"); if (env_ptr != NULL)

strcpy(lib_path, env_ptr);

else

/* prompt user for shared library path */

{

 

 

printf("Shared library to use >> ");

 

scanf("%s", lib_path);

}

 

}

 

/*

 

*Dynamically load the shared library using BIND_IMMEDIATE binding:

*/

lib_handle = shl_load( lib_path, BIND_IMMEDIATE, 0); if (lib_handle == NULL)

170 Shared Library Management Routines