C++调用动态库.so(不存在.h时)

下文展示当提供头文件(.h)时,C++如何调用.so库。

第一部分:创建动态库

举个栗子:
test.cpp (动态库的源文件)
#include <iostream>

extern "C" {
    int sum(int a, int b) {
        return a + b;
    }
}

编译生成动态库 libtest.so:

g++ -fPIC -shared -o libtest.so test.cpp

至此动态库创建已经完成。

第二部分:调用动态库

编写一个 C++ 程序,使用 dlopen 和 dlsym 加载并调用 sum 函数:

main.cpp:

#include <iostream>
#include <dlfcn.h>  // 包含动态加载库的头文件

typedef int (*sum_func)(int, int);  // 定义函数指针类型

int main() {
    // 打开动态库
    void* handle = dlopen("./libtest.so", RTLD_LAZY);
    if (!handle) {
        std::cerr << "Failed to load library: " << dlerror() << std::endl;
        return -1;
    }

    // 获取 sum 函数的地址
    dlerror();  // 清除之前的错误
    sum_func sum = (sum_func) dlsym(handle, "sum");
    const char* error = dlerror();
    if (error) {
        std::cerr << "Failed to load symbol: " << error << std::endl;
        dlclose(handle);
        return -1;
    }

    // 调用 sum 函数
    int result = sum(10, 20);
    std::cout << "Sum of 10 and 20 is: " << result << std::endl;

    // 关闭动态库
    dlclose(handle);
    return 0;
}

1 编译程序

g++ -o main main.cpp -ldl

2 运行程序
确保 libtest.so 文件在当前目录下,或者将其路径添加到环境变量 LD_LIBRARY_PATH 中.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值