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

std::string cannot be printed in gdb when it's global variable, why?

本文关键字:打印 为什么 gdb 不能 string 全局变量 std      更新时间:2023-10-16

我有一个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 .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 hello "将工作,如果我调试它。这对我来说太奇怪了。

为什么没有符号?

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

我想当有一个名为" hello "的符号时:

shell应该出现在ELF文件的符号表中,对吗?

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

你应该试试:

$ readelf -w a.out | fgrep sHello
<2fd3>   DW_AT_name        : (indirect string, offset: 0xce6): sHello

-w开关显示文件中调试部分的内容,如果有的话。

为什么没有符号?

原因可能是编译器和调试器不匹配。

我无法重现这个问题(使用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上你会得到预期的行为

相关文章: