c++ - 为什么在链接时不解析共享库的符号?

标签 c++ c linux gcc linker

这是我在本网站上的第 2 篇文章,旨在了解 gcc 的编译/链接过程。当我尝试制作可执行文件时,符号需要在链接时解析,但是当我尝试制作共享库时,符号不会在该库的链接时解析。当我尝试使用此共享库制作可执行文件时,它们可能会得到解决。动手:

bash$ cat printhello.c
#include <stdio.h>
//#include "look.h"

void PrintHello()
{
look();
printf("Hello World\n");
}

bash$ cat printbye.c
#include <stdio.h>
//#include "look.h"

void PrintBye()
{
look();
printf("Bye bye\n");
}

bash$  cat look.h
void look();

bash$ cat look.c
#include <stdio.h>

void look()
{
printf("Looking\n");
}

bash$ gcc printhello.c printbye.c
/usr/lib/gcc/i386-redhat-linux/4.1.2/../../../crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
/tmp/cck21S0u.o: In function `PrintHello':
printhello.c:(.text+0x7): undefined reference to `look'
/tmp/ccNWbCnd.o: In function `PrintBye':
printbye.c:(.text+0x7): undefined reference to `look'
collect2: ld returned 1 exit status

bash$ gcc -Wall -shared -o libgreet printhello.c printbye.c
printhello.c: In function 'PrintHello':
printhello.c:6: warning: implicit declaration of function 'look'
printbye.c: In function 'PrintBye':
printbye.c:5: warning: implicit declaration of function 'look'

所以我的问题是为什么在链接共享库时符号没有解析。这个工作(Resolving symbols of its downstream)在我用这个库做一个可执行文件的时候需要做,但是这意味着我们在使用这个库的时候需要知道这个库依赖什么,但这不是不可取的吗?

谢谢, 贾格拉蒂

最佳答案

在构建库时添加 -z defs 是否符合您的要求?如果没有,请查看 ld 手册页,有很多关于处理 undefined symbol 的选项。

关于c++ - 为什么在链接时不解析共享库的符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3159395/

相关文章:

c++ - 如何使用 IOCP 获取客户端真实 IP 地址和端口?

c++ - 你能改变 Qt 连接的队列大小吗?

c - 无法增加指针

c - C : 2 Clients and 1 Server 中的 UDP 套接字编程

c - 如何在使用 recvmsg() 时从 UDP 数据包中检索源端口

c++ - 如何使用版本名称将二进制文件与库链接

c++ - 如何将文件存储在可执行文件中

c++ - 保存图像而不压缩

linux - 如何从 bz2 存档中获取文件列表(ls 命令)?

c - 我如何像 "top"命令那样获取每个 CPU 的统计信息(系统、空闲、良好...)?