Linux C language: dynamically load library functions when the program is running

Source: Internet
Author: User

PS: For more information, see the man manual. Here we only provide one instance and the steps for creating this instance.

1: Create the test. h and test. c files.

 
// Test. h # ifndef test_h _ # define test_h _ # include <stdio. h> void printhello (); int add (int A, int B); # endif

 
// Test. CPP # include "test. H "// output text hello, worldvoid Hello () {printf (" Hello, world \ n ");} // returns the sum of the two parameters and INT add (int, int B) {return a + B ;}

2: compile it into a dynamic library

 
GCC test. C-shared-FPIC-O libtest. So

3: Create main file main. c

// Main. C # include <stdio. h> # include <stdlib. h> # include <dlfcn. h> # include <signal. h> # include <errno. h> // output the error message and exit void error_quit (const char * Str) {fprintf (stderr, "% s \ n", STR); exit (1 );} int main (INT argc, char * argv []) {void * plib; // pointer to so file typedef void (* fun_hello) (); typedef int (* fun_add) (INT, INT); fun_hello funhello = NULL; // function pointer fun_add funadd = NULL; // open the so file // For ease of demonstration, I put the library file and executable file in the same directory plib = dlopen (". /libtest. so ", rtld_now | rtld_global); If (null = plib) error_quit (" can't open the libtest. so "); // load function void Hello () funhello = dlsym (plib," hello "); If (null = funhello) error_quit ("can't load function 'hello'"); // load function int add (int A, int B) funadd = dlsym (plib, "add "); if (null = funadd) error_quit ("can't load function 'add'"); // call the function funhello () that is successfully loaded (); printf ("5 + 8 = % d \ n", funadd (5, 8); // close the so file dlclose (plib); Return 0 ;}

4: Compile and run

GCC main. C-o main-LDL./main

Finished.

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.