【问题标题】:Why does -Wl,--entry work with gcc, but not g++?为什么 -Wl,--entry 与 gcc 一起工作,而不是 g++?
【发布时间】: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 的文件中是相当不寻常的。

标签: c++ c gcc g++


【解决方案1】:

由于名称修改,函数不是not_main,而是_Z8not_mainv

g++ 与 gcc 有何不同,

What is the difference between g++ and gcc? why use g++ instead of gcc to compile *.cc files?

【讨论】:

  • 谢谢,这似乎可以解决问题。名称修改是否有规则,以便我可以预测名称?我通常使用 C,所以在头文件中我使用 extern "C" 以防它被编译为 C++。这会解决名称修改问题吗?
  • 你最好使用exrern "C"。安怀:itanium-cxx-abi.github.io/cxx-abi/abi.html
【解决方案2】:

与 C 不同,C++ 使用名称修改区分相同函数名的不同重载。

使用gcc 编译时:

$ objdump -t entry.o | grep not_main
000000000000117c g     F .text  0000000000000036              not_main

使用g++ 编译时:

$ objdump -t entry.o | grep not_main
0000000000000000         *UND*  0000000000000000              not_main
000000000000117c g     F .text  0000000000000036              _Z8not_mainv

*UND*efined 对 not_main 的引用可能由链接器放置在那里,因为您请求将其作为入口点。实际的not_main 函数的名称被修改为_Z8not_mainv

要以其原始名称导出 not_main,请使用 extern "C"

extern "C" int not_main()
{
    printf("Entering %s:%s
", __FILE__, __func__);
    exit(0); // Necessary, otherwise it throws a segfault
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多