linux 使用动态链接库

实验源文件

头文件 test_so.h

#include "stdio.h"
void test_a();
void test_b();
void test_c();

test_a.cpp test_b.cpp test_c.cpp 都如下所示

#include "test_so.h"
void test_a()
{
	printf("this is in test_a...\n");
}

主文件 test.cpp

#include "test_so.h"
int main()
{
	test_a();
	test_b();
	test_c();
	return 0;
}

编译 so

使用 g++ test_a.cpp test_b.cpp test_c.cpp -fPIC -shared -o libtitus.so 编译动态链接库 libtitus.so。

  • -fPIC 选项表示编译为位置独立的代码,不用此选项的话编译后的代码是位置相关的所以动态载入时是通过代码拷贝的方式来满足不同进程的需要,而不能达到真正代码段共享的目的

  • -shared 选项表示生成 .so 形式的动态链接库

使用 so

使用 g++ test.cpp -L. -ltitus -o test 将 test.cpp 和libtitus.so 编译链接生成可执行的 test 文件。

  • -L. 为执行链接指定一个库的路径(当前路径)
  • -ltitus 为执行链接指定具体的库 libtitus.so,只需要写为 titus

这时生成了 test 文件,使用 ldd test 查看调用关系

linux-vdso.so.1 =>  (0x00007fff77655000)
libtitus.so => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 
(0x00007f64e54fe000)
/lib64/ld-linux-x86-64.so.2 (0x00007f64e58eb000)

发现找不到 libtitus.so。执行 ./test

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

还需要执行

export LD_LIBRARY_PATH=/home/hy/Practice/C++/SearchCenter:

将此动态库的目录加入到环境变量中。LD_LIBRARY_PATH 这个环境变量指示动态连接器可以装载动态库的路径,也就是程序运行时去找 so 文件的路径。

参考

linux下c++的编译器g++的基本使用

转载于:https://my.oschina.net/lvyi/blog/725925

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值