这是我在本网站上的第 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/