ChorusOS 4.0 Introduction

Explicit Link Using dlopen

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

This 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 ("", RTLD_NOW);
    if !(handle) { printf ("Cannot find library\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 */

This 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 above are built in the same way as in the previous example, using two Imakefiles:

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

SRCS = libdyn2.c
DynamicLibraryTarget (, libdyn2.o, , , , )

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

SRCS = progdyn2.c
DynamicUserTarget (progdyn2, progdyn2.o, , , , )

Running the Dynamic Program

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

% cp $WORK/progdyn2dir/progdyn2 chorus_root_directory/bin 

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

% cp $WORK/libdyn2dir/ chorus_root_directory/lib 

Then, the following command will tell the runtime linker where to find the dynamic library:

% rsh jericho setenv LD_LIBRARY_PATH /lib

Finally, the following command will start the program:

% rsh jericho arun /bin/progdyn2 

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