当前位置:网站首页>GCC:屏蔽动态库之间的依赖
GCC:屏蔽动态库之间的依赖
2022-08-05 00:40:00 【风静如云】
假设有如下依赖关系的一个程序:
m 依赖于a
a 依赖于b
//a.c
#include <stdio.h>
void b();
void a()
{
printf("Here is a call b\n");
b();
//b.c
#include <stdio.h>
void b()
{
printf("Here is b\n");
//m.c
#include <stdio.h>
void a();
int main()
{
a();
return 0;
已经说明此程序应该编译连接。
但是这里有一个地方并不是十分的方便,就是m从表面上看只依赖a,却需要将a依赖的b在编译连接时也加入,方可运行。对于一个比较复杂的程序,那么就需要不断的查看程序,才能确认最终需要编译连接的库都有什么,及其的不方便。
那么可不可以将a的依赖需要放入a的编译过程中呢:
gcc -fpic -shared a.c -o liba.so -lb -L .
gcc -o m m.c -la -L.
由于连接时库a需要库b,却无法找到,因此报错:
/usr/bin/ld: warning: libb.so, needed by ./liba.so, not found (try using -rpath or -rpath-link)
/usr/bin/ld: ./liba.so: undefined reference to `b'
collect2: error: ld returned 1 exit status
ldd liba.so
linux-vdso.so.1 (0x00007ffecb1fd000)
libb.so => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f2ba19ad000)
/lib64/ld-linux-x86-64.so.2 (0x00007f2ba1bb7000)
可见这种方式行不通。
解决这个问题可以通过-Wl,-rpath=
-WL:表示编译器将后面的参数传递给链接器ld
-rpath:用于指定编译连接和运行时依赖的路径
因此编译a时可以通过如下方式,将其依赖的b加入:
gcc -fpic -shared a.c -o liba.so -lb -Wl,-rpath=.
gcc -o m m.c -la -L .
注:以上编译后,运行时可能会报错:
./m: error while loading shared libraries: liba.so: cannot open shared object file: No such file or directory
其原因是在运行时无法找到liba.so
解决这个问题有两个方法:
1.通过设置LD_LIBRARY_PATH
export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH
2.编译m时也指定 -Wl,-rpath=,即:
gcc -o m m.c -la -Wl,-rpath=.
边栏推荐
- gorm的Raw与scan
- Software Testing Interview Questions: What Are the Types of Software Testing?
- 倒计时1天!8月2日—4日与你聊聊开源与就业那些事!
- Software Testing Interview Questions: About Automated Testing Tools?
- The method of freely controlling concurrency in the sync package in GO
- MAUI Blazor 权限经验分享 (定位,使用相机)
- 标识符、关键字、常量 和变量(C语言)
- tensor.nozero(),面具,面具
- 2022牛客多校第三场 A Ancestor
- 数据类型及输入输出初探(C语言)
猜你喜欢
随机推荐
[230] Execute command error after connecting to Redis MISCONF Redis is configured to save RDB snapshots
matlab中rcosdesign函数升余弦滚降成型滤波器
软件测试面试题:什么是软件测试?软件测试的目的与原则?
Will domestic websites use Hong Kong servers be blocked?
Software Testing Interview Questions: Qualifying Criteria for Software Acceptance Testing?
tiup uninstall
关于我仔细检查审核过关于工作人员页面,返回一个所属行业问题
2022牛客多校训练第二场 H题 Take the Elevator
数据类型-整型(C语言)
E - Many Operations (bitwise consideration + dp thought to record the result after the operation
SV 类的虚方法 多态
软件测试面试题:软件都有多少种分类?
Software Testing Interview Questions: About Automated Testing Tools?
软件测试面试题:一套完整的测试应该由哪些阶段组成?
[FreeRTOS] FreeRTOS and stm32 built-in stack occupancy
Software Testing Interview Questions: What aspects should be considered when designing test cases, i.e. what aspects should different test cases test against?
leetcode:266. 回文全排列
Countdown to 1 day!From August 2nd to 4th, I will talk with you about open source and employment!
软件测试面试题:黑盒测试、白盒测试以及单元测试、集成测试、系统测试、验收测试的区别与联系?
oracle创建用户以后的权限问题