linux c dlopen loads a dynamic link library

// file : add.c
int add(int a, int b) { return a+b; };

// cmd: gcc -shared -o libadd.so add.c -fPIC
 // compiled dynamic library files

// File: demo.c 
#include <stdio.h>   
#include <stdlib.h>    // EXIT_FAILURE 
#include <dlfcn.h>     // dlopen, dlerror, dlsym, dlclose 

typedef int (* FUNC_ADD) ( int , int ); // define the function pointer type alias 
const  char * DLLPath = " ./libadd.so " ;

int main ()
{
    void* handle = dlopen( dllPath, RTLD_LAZY );

    if( !handle )
    {
        fprintf( stderr, "[%s](%d) dlopen get error: %s\n", __FILE__, __LINE__, dlerror() );
        exit( EXIT_FAILURE );
    }

    do{ // for resource handle
        FUNC_ADD add_func = (FUNC_ADD)dlsym( handle, "add" );
        printf( "1 add 2 is %d \n", add_func(1,2) );
    }while(0); // for resource handle
    dlclose( handle );
}
// cmd   : gcc -o demo demo.c -ldl; ./demo
// output: 1 add 2 is 3

 

Guess you like

Origin www.cnblogs.com/whutqueqiaoxian/p/12029751.html