Linux 下动态库生成 及dlopen、dlsym方式加载使用

一、生成动态库
calculate.c文件

int add(int a, int b)
{
    return a+b;
}

int sub(int a, int b)
{
    return a-b;
}

int mul(int a, int b)
{
    return a*b;
}

float div(int a, int b)
{
    return a / b;
}      

编译生成动态库
gcc -fPIC -shared caculate.c -o libcaculate.so

二、直接链接动态库

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main(void)
{
    printf("2+2 = %d\n", add(2,2));
    printf("10-2 = %d\n", sub(10,2));
}                                                                          

使用步骤如下:
1、export LD_LIBRARY_PATH=.
否则会出现error while loading shared libraries: lib*.so: cannot open shared object file: No such file or directory
2、gcc test_dlopen.c -L . -lcaculate -o test_dlopen
3、执行./test_dlopen

三、使用dlopen函数加载
相关说明:

#include <dlfcn.h>
void *dlopen(const char *filename, int flags);
flags:
RTLD_LAZY 暂缓决定,等有需要时再解出符号 
RTLD_NOW 立即决定,返回前解除所有未决定的符号。
int dlclose(void *handle);
char *dlerror(void);
void *dlsym(void *handle, const char *symbol);

示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>

typedef int (*cal) (int, int);
void main(void)
{   
    void *handle;
    handle = dlopen("./libcalculate.so", RTLD_LAZY);
    if (handle == NULL) {
        fprintf(stderr, "%s\n",dlerror());
        return ;
    }

    cal add = dlsym(handle, "add");
    printf("%d\n", add(1,2));
    
    cal sub = dlsym(handle, "sub");
    printf("%d\n", sub(10,2));
    
    dlclose(handle);
}

执行命令:
gcc test_dlopen2.c -ldl -o test_dlopen2
./test_dlopen2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值