【发布时间】:2023-01-27 19:09:51
【问题描述】:
我正在尝试编译一个程序,以便它从不同的入口点开始。我在 Ubuntu 20.04.5、GCC 和 G++ 9.4.0 上运行 WSL1
我发现在编译器中添加标志-Wl,--entry=foo会链接foo()作为入口函数。测试,这适用于 gcc,但不适用于 g++。
使用示例文件 src/main.c:
#include <stdlib.h>
#include <stdio.h>
int main()
{
printf("Entering %s:%s\n", __FILE__, __func__);
return 0;
}
int not_main()
{
printf("Entering %s:%s\n", __FILE__, __func__);
exit(0); // Necessary, otherwise it throws a segfault
}
当使用 gcc -Wl,--entry=not_main -o entry.o src/main.c 编译时,输出是我想要的:Entering src/main.c:not_main。
但是用g++ -Wl,--entry=not_main -o entry.o src/main.c编译时,出现如下警告:/usr/bin/ld: warning: cannot find entry symbol not_main; defaulting to 0000000000001080。
这默认为main()函数,输出Entering src/main.c:main。链接器未找到函数not_main(),但它存在于源代码中。
g++ 的文档说:
g++ 是一个调用 GCC 并自动指定针对 C++ 库的链接的程序。
如果在内部调用另一个,我看不出 g++ 与 gcc 有何不同。我知道改变入口点的不是编译器而是链接器,g++(与 gcc 不同)正在链接 C++ 库,但我不明白这是怎么回事。
我错过了什么?
【问题讨论】:
-
并不是说它会导致这个问题,而是将最终链接的可执行文件发送到名为
entry.o的文件中是相当不寻常的。