Linux c语言程序运行时动态加载库函数

来源:互联网 发布:李宁淘宝旗舰店 编辑:程序博客网 时间:2024/05/17 05:09

*注明:内容来自网络整理自用

一、创建test.c test.h

//test.c

#include <stdio.h>#include <stdlib.h>void PrintHello(){    printf("Hello\n");}int Add(int a, int b){    int nk = 0;    nk = a + b;    return nk;}

//test.h

#ifndef _TEST_H_#define _TEST_H_#include <stdio.h>void PrintHello();int Add(int a, int b);#endif 

2:编译成动态库

gcc test.c -shared -fPIC -o libtest.so

3:创建主文件main.c

#include <stdio.h>#include <stdlib.h>#include <dlfcn.h>#include <signal.h>#include <errno.h>//输出错误的信息并退出void error_quit(const char *str){    fprintf(stderr, "%s\n", str);    exit(1);}int main(int argc, char *argv[]){    void *plib;//指向SO文件的指针    typedef void(*FUN_HELLO)();    typedef int(*FUN_ADD)(int, int);    FUN_HELLO funHello = NULL; //函数指针    FUN_ADD funAdd = NULL;    //打开so文件    plib = dlopen("./libtest.so", RTLD_NOW|RTLD_GLOBAL);    if(NULL ==  plib)        error_quit("Can`t open the libtest.so");    //加载函数 void PrintHello()    funHello = dlsym(plib, "PrintHello");    if(NULL == funHello)        error_quit("Can`t load function 'PrintHello'");    //加载函数 int Add(int a, int b)    funAdd = dlsym(plib, "Add");    if(NULL == funAdd)        error_quit("Can`t load fubction 'Add'");    //调用成功加载函数    funHello();    printf("5 + 8 = %d\n", funAdd(5, 8));    //关闭so文件    dlclose(plib);    return 0;}

4:编译并运行

gcc main.c -o main -ldl
./main
结果:
ysq@ysq-Box:~/code/test$ ./main
Hello
5 + 8 = 13

原创粉丝点击