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.