Dependency between dlopen and dynamic link library

Source: Internet
Author: User

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.