gpt4 book ai didi

c++ - std::string 是全局变量时不能在 gdb 中打印,为什么?

转载 作者:行者123 更新时间:2023-11-30 05:21:24 42 4
gpt4 key购买 nike

我有一个 teststring.cpp 文件,我想看看 gdb 是否可以输出 std::string 值:

#include<string>
#include<iostream>
using namespace std;
string sHello="hello world";
int main()
{
cout<<sHello.c_str()<<endl;
return 0;
}

使用 g++ teststring.cpp -g 和 gdb a.out

(gdb) b main
Breakpoint 1 at 0x400bfa: file teststring.cpp, line 7.
(gdb) r
Starting program: /home/x/a.out

Breakpoint 1, main () at teststring.cpp:7
7 cout<<sHello.c_str()<<endl;
(gdb) p sHello
No symbol "sHello" in current context.

这很奇怪。如果我移动

string sHello="hello world";

作为main的第一行,像这样:

#include<string>
#include<iostream>
using namespace std;
int main()
{
string sHello="hello world";
cout<<sHello.c_str()<<endl;
return 0;
}

如果我调试它,“p sHello”就会工作。嗯,这对我来说太奇怪了。

Why it says no symbol?

更奇怪的是,我用“$ readelf -s a.out|grep sHello”来检查a.out的两个版本,都没有给我任何结果。

我想当有一个名为“sHello”的符号时:

sHello should appear in symbol table of ELF file, right?

最佳答案

More strange is, I used "$ readelf -s a.out|grep sHello" to check both versions of a.out, neither of them give me any result.

你应该尝试:

$ readelf -w a.out | fgrep sHello

<2fd3> DW_AT_name : (indirect string, offset: 0xce6): sHello

-w 开关显示文件中调试部分的内容(如果存在)。

Why it says no symbol?

罪魁祸首可能是编译器和调试器之间的不匹配。

我无法重现该问题(使用 g++ v5.4.0 和 gdb 7.11.1):

(gdb) p sHello
$3 = {static npos = <optimized out>,
_M_dataplus = {<std::allocator<char>> =
{<__gnu_cxx::new_allocator<char>> = {<No data fields>},
<No data fields>},
_M_p = 0x614c38 "hello world"}}

也许在更高版本的 GDB 上你会得到预期的行为。

关于c++ - std::string 是全局变量时不能在 gdb 中打印,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40172071/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com