在Linux环境下关于c++动态库.so

  1. 准备一些简单的代码

这些文件都处于同一目录下
test.h声明了一个函数

#include<iostream>
#include<string>

void My_Print(std::string str);

test.cpp负责实现头文件的函数

#include"test.h"
void My_Print(std::string str)
{
    std::cout<<str<<std::endl;
}

tt.cpp用于测试的文件

#include"test.h"

int main()
{
    My_Print("hello world");
    return 0;
}
  1. 编译运行这个文件
    g++ ./tt.cpp -o tt
    出现报错
/usr/bin/ld: /tmp/ccUJfOAd.o: in function `main':
tt.cpp:(.text+0x4a): undefined reference to `My_Print(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: error: ld returned 1 exit status

因为没找到函数的实现。
添加上函数实现的文件test.cpp
g++ ./tt.cpp -o tt test.cpp
成功编译并运行。

  1. 将其打包成.so动态库
    使用命令g++ -fPIC -shared test.cpp -o libmy_test.so
    就在当前目录生成了一个libmy_test.so*动态库
    使用.so生成tt文件
    g++ tt.cpp -o tt ./libmy_test.so
    现在已经成功了一半,如果要分享给别人自己实现的库,就可以将.h文件和.so文件传给他就行了。

  2. 在环境中配置动态库
    在linux上,通常在/usr/lib/usr/local/lib 下寻找.a.so 文件
    /usr/include /usr/local/include 下找 *.h文件

  • 我们执行sudo mv ~/projects/test/libmy_test.so /usr/local/lib/
    sudo mv ~/projects/test/test.h /usr/local/include/
    将头文件和cpp文件移动到这些地方。

  • 这时候我们使用动态库重新编译测试文件
    g++ ./tt.cpp -o tt -lmy_test

  • 编译成功,但是运行出现报错:
    ./tt: error while loading shared libraries: libmy_test.so: cannot open shared object file: No such file or directory
    这个表示在运行的时候找不到这个libmy_test.so文件,编译的时候寻找文件是在 /usr/lib寻找 ,但是运行的时候是在 /etc下的文件中寻找。

  • /etc/ld.so.cache运行的时候.so库都会在这个缓存文件中寻找.

  • 我们打开vim ./ld.so.conf发现
    在这里插入图片描述
    这段路径表示包括/etc/ld.so.conf.d所有的.conf文件。
    这个ld.so.conf.d就是配置.so的关键。

  • cd ld.so.conf.d
    vim mylib.conf 创建自己的conf文件
    写入/usr/local/lib也就是之前.so保存的路径。
    sudo ldconfig将配置写入缓存。
    就会发现之前编译出的tt可以正常运行了。
    在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值