ChorusOS 5.0 Application Developer's Guide

Explicit Link of a Dynamic Library Using dlopen

The following program explicitly loads a dynamic library at runtime using the function dlopen(). This program searches for the address of the dynfunc() function (defined in the library) and calls this function.

The following is the dynamic program progdyn2.c:

#include <chorus.h>
#include <cx/dlfcn.h>

int main()
{
    void    (*funcptr)();       /* pointer to function to search */
    void    *handle;            /* handle to the dynamic library */

        /* finding the library */
    handle = dlopen ("libdyn2.so", RTLD_NOW);
    if !(handle) { printf ("Cannot find library libdyn2.so\n"); exit(1); } 

        /* finding the function in the library */
    funcptr = (void (*)()) dlsym (handle, "dynfunc");
    if !(funcptr) { printf ("Cannot find function dynfunc\n"); exit(1); }

        /* calling library function */
    (*funcptr)();
}

The following is the dynamic library libdyn2.c:

#include <chorus.h> 

void dynfunc() {
    printf ("Calling dynfunc\n");
}
Building the Program and the Library

The program and library discussed in the previous section are built in the same way as the previous example using two Imakefiles:

  1. Create the first directory.

    Create a directory called libdyn2dir in $WORK, containing libdyn2.c and the following Imakefile:

    SRCS = libdyn2.c
    DynamicLibraryTarget (libdyn2.so, libdyn2.o, , , , )
    Depend(libdyn2.c)
  2. Create the second directory.

    Create a directory progdyn2dir in $WORK, containing progdyn2.c and the following Imakefile:

    SRCS = progdyn2.c
    DynamicUserTarget (progdyn2, progdyn2.o, , , , )
    Depend(progdyn2.c)
Running the Dynamic Program
  1. Copy the program.

    Copy the dynamic program into the /bin subdirectory of the chorus_root_directory directory:


    % cp $WORK/progdyn2dir/progdyn2 chorus_root_directory/bin 
    
  2. Copy the library.

    Copy the dynamic library into the /lib subdirectory of the chorus_root_directory directory:


    % cp $WORK/libdyn2dir/libdyn2.so chorus_root_directory/lib 
    
  3. Notify the runtime linker.

    Use the following command to notify the runtime linker where to find the libdyn2.so dynamic library:


    % rsh jericho setenv LD_LIBRARY_PATH /lib
    
  4. Start the program.

    Use the following command to start the program:


    % rsh jericho arun /bin/progdyn2 
    

    At program start-up, the runtime linker will only load the progdyn2 executable . The libdyn2.so library is loaded when the dlopen() function is called.