c++调用.so库

1. g++进行编译并调用.so库

目录/home/test_ws/src/

文件1:

test1.h

#include <iostream>
using namespace std;
void test();

文件2:

test1.cpp

#include "test1.h"
void test()
{
    std::cout << "this is a test log" << std::endl;
}

文件3:

main.cpp

#include "test1.h"
int main()
{
    test();
}
g++ -std=c++11 test1.cpp -shared -fPIC -o test1.so  #在src下生成test1.so的动态库文件

g++ main.cpp test1.so -o main  #在src下生成main的可执行文件

./main会报错

./main: error while loading shared libraries: test1.so: cannot open shared object file: No such file or directory

这是因为链接器ld默认的目录是/lib和/usr/lib,如果放在其他路径也可以,需要让ld知道库文件在哪里。 

使用如下命令

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/test_ws/src/

将存放test1.so的文件夹导入到ld连接器中即可,但是计算机重启将会失效,需要重新导入。

运行

./main

结果

this is a test log

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值