生成并调用so动态库

本文更新于2019-01-03。

生成库

头文件fn.h如下:

#ifndef __FN_H__
#define __FN_H__

#ifdef __cplusplus
extern "C"
{
#endif

typedef int (*FnAdd)(int a, int b);

int add(int a, int b);

#ifdef __cplusplus
}
#endif

#endif // __FN_H__

源文件fn.c如下:

#include "fn.h"

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

编译生成libfn.so库:

gcc -fPIC -shared fn.c -o libfn.so

若不使用extern "C",且使用g++编译或使用gcc编译cpp文件,则生成C++形式的库。

调用库

源文件main.c如下:

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

#include "fn.h"

int main() {
    void* handle = dlopen("./libfn.so", RTLD_LAZY);
    if (handle == NULL) {
        printf("dlopen: %s\n", dlerror());
        return -1;
    }
    
    FnAdd add = (FnAdd)dlsym(handle, "add");
    if (add == NULL) {
        printf("dlsym: %s\n", dlerror());
        return -1;
    }
    
    int a = 1;
    int b = 2;
    printf("add %d+%d=%d\n", a, b, add(a, b));

    dlclose(handle);
    return 0;
}

编译生成可执行文件a.out:

gcc -rdynamic -ldl main.c -o a.out

如使用dlopen调用库时没指定库文件路径,只指定库文件名(如libfn.so),则执行程序前需导出环境变量LD_LIBRARY_PATH,将库文件所在目录加入其中。

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:dir

转载于:https://www.cnblogs.com/garvenc/p/build_and_call_so_library.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值