There are two dynamic link libraries, one of which depends on another defined function. When using dlopen, you need to add RTLD_GLOBAL.
Dynamic library 1, life, defines a life function.
Gcc-shared-Wl,-soname, liblife. so.1-o liblife. so.1.0 life. c
---------------------------------------------------------------------
# Include <stdio. h>
# Include <stdlib. h>
# Include <dlfcn. h>
Int life (int)
{
Return a + 8;
}
Dynamic library 2, printk, which calls the life function of the dynamic library.
Gcc-shared-Wl,-soname, libprintk. so.1-o libprintk. so.1.0 printk. c
----------------------------------------------------------------------
# Include <stdio. h>
# Include <stdlib. h>
# Include <dlfcn. h>
Extern int life (int );
Void printk (char * con)
{
Printf ("% s % d/n", con, life (1 ));
Return;
}
Main Program, opened two dynamic link libraries with dlopen
Gcc-o foo. c-ldl
-------------------------------------------------------------------
# Include <stdio. h>
# Include <stdlib. h>
# Include <dlfcn. h>
Int day (int)
{
Return a + 2;
}
Int main (int argc, char ** argv ){
Void * handle1, * handle2;
Void (* printk) (char *);
Int (* life) (int );
Char * error;
Handle2 = dlopen ("./liblife. so.1.0", RTLD_LAZY |RTLD_GLOBAL
);
If (! Handle2 ){
Fprintf (stderr, "% s/n", dlerror ());
Exit (1 );
}
Dlerror ();/* clear any existing Error */
Handle1 = dlopen ("./libprintk. so.1.0", rtld_lazy |RTLD_GLOBAL
);
If (! Handle1 ){
Fprintf (stderr, "% s/n", dlerror ());
Exit (1 );
}
Dlerror ();/* clear any existing Error */
Life = dlsym (handle2, "life ");
If (error = dlerror ())! = NULL ){
Fprintf (stderr, "% s/n", error );
Exit (1 );
}
Printk = dlsym (handle1, "printk ");
If (error = dlerror ())! = NULL ){
Fprintf (stderr, "% s/n", error );
Exit (1 );
}
Printf ("% d/n", life (1 ));
Printk ("hhh ");
Dlclose (handle1 );
Dlclose (handle2 );
Return 0;
}