c++ - 是否有 "simple"方法让 ld 输出 demangle 函数名称?

标签 c++ c++-faq

我发现必须修复链接时发生的 C++ 错误(尤其是 undefined reference 错误)非常令人沮丧,因为所有函数名称都被破坏了。错误名称的示例:

_ZNK5boost7archive6detail11oserializerINS0_13text_oarchiveEN9galandria8UniverseEE16save_object_dataERNS1_14basic_oarchiveEPKv
读起来太难了,找到真正的功能就更难了。
有没有办法说服ld输出损坏的名称?

最佳答案

ld (GNU 链接器)能够对 C++ 函数名称进行解密。 ld关于从它拆解的文档 man页面:(可用here在线)

       --demangle[=style]
       --no-demangle
           These options control whether to demangle symbol names in error
           messages and other output.  When the linker is told to demangle,
           it tries to present symbol names in a readable fashion: it strips
           leading underscores if they are used by the object file format,
           and converts C++ mangled symbol names into user readable names.
           Different compilers have different mangling styles.  The optional
           demangling style argument can be used to choose an appropriate
           demangling style for your compiler.  The linker will demangle by
           default unless the environment variable COLLECT_NO_DEMANGLE is
           set.  These options may be used to override the default.
让我们看一个例子:
void foo();
void foo(int);
int main() {
    foo();
    foo(5);
}
这是一个简单的有效代码。这将编译但无法成功链接,因为没有实现 foo()foo(int)这里。现在我们将使用以下命令编译它:
g++ main.cpp -c -o main.o
它将成功编译。现在让我们尝试使用以下命令将其与禁用 demanling 链接起来:
g++ main.o -Wl,--no-demangle
它应该显示带有一些奇怪的错误名称的链接错误,如下所示:
main.o: In function `main':
main.cpp:(.text+0x5): undefined reference to `_Z3foov'
main.cpp:(.text+0xf): undefined reference to `_Z3fooi'
collect2: error: ld returned 1 exit status
See live on Coliru
现在让我们尝试使用以下命令启用 demanling 链接:
g++ main.o -Wl,--demangle
我们将收到带有如下参数的解构函数名称的错误:
main.o: In function `main':
main.cpp:(.text+0x5): undefined reference to `foo()'
main.cpp:(.text+0xf): undefined reference to `foo(int)'
collect2: error: ld returned 1 exit status
See live on Coliru
这里-Wl表示链接器的参数。
据我所知,g++启用自动拆线。

关于c++ - 是否有 "simple"方法让 ld 输出 demangle 函数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64122365/

相关文章:

c++ - 为什么结构体的 sizeof 不等于每个成员的 sizeof 之和?

c++ - 适用于 PostgreSQL 的优秀 C/C++ 连接器库

c++ - Linux 真的分配了它不应该在 C++ 代码中的内存

c++ - 什么是三法则?

c++ - 什么是复制省略和返回值优化?

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - 无法使用 bash 脚本正确重启应用程序

C++ 从字符串化字节转换字节数组

c++ - 在 C++ 中将长字符串输出到文件

c++ - 为什么只能在头文件中实现模板?