2008-10-31 50 views
185

我想检查GDB中的std::vector的内容,我该如何做?为了简单起见,假设它是一个std::vector<int>如何在GDB中打印C++向量的元素?

+3

类似的问题:HTTP://计算器.com/questions/427589/inspecting-standard-container-stdmap-contents-with-gdb(答案中的链接非常有趣)。 – 2009-06-26 15:47:49

+0

新的,更好的方法是在这个问题中:http://stackoverflow.com/questions/2492020/how-to-view-contents-of-stl-containers-using-gdb-7-x/2492341# 2492341 – dshepherd 2013-04-19 11:19:09

+0

非矢量特定:https://stackoverflow.com/questions/427589/inspecting-standard-container-stdmap-contents-with-gdb – 2017-09-24 10:29:36

回答

68

编译要查看矢量的std ::矢量myVector内容,只是在类型GDB:

(gdb) print myVector 

这将产生类似的输出:

$1 = std::vector of length 3, capacity 4 = {10, 20, 30} 

为了达到上述目的,你需要有gdb 7(我在gdb 7.01上测试过)和一些python漂亮的打印机。这些的安装过程在gdb wiki上描述。

更重要的是,上述安装后,这与Eclipse的 C++调试器GUI效果很好(使用GDB任何其他的IDE,因为我认为)。

230

随着GCC 4.1.2,打印整个一个std ::的矢量<INT>名为myVector,执行下列操作:

print *(myVector._M_impl._M_start)@myVector.size() 

要打印只有第一N个元素,如下:

print *(myVector._M_impl._M_start)@N 

说明

这可能是严重依赖于你的编译器版本,但对于GCC 4.1.2,指针到内部阵列是:

myVector._M_impl._M_start 

而GDB命令到阵列的打印N个元件开始在指针P是:

print [email protected] 

或者,在一个简短的格式(对于一个标准的.gdbinit):

p [email protected] 
+3

呵呵,这是我之前的事情,所以我只是今天早上看它了并作为备忘录添加到自己(如杰夫本人推荐)。 – 2008-10-31 11:10:42

+2

另外,如果你只想要一个特定的向量元素,myVector._M_impl._M_start + n(对于第n个元素) – mariner 2014-01-07 01:26:43

13

在调试时看着'STL容器是有点问题。以下是我过去使用的3种不同的解决方案,其中没有一个是完美的。

1)使用http://clith.com/gdb_stl_utils/的GDB脚本这些脚本允许您打印几乎所有STL容器的内容。问题在于,这对嵌套容器(如堆栈集合)不起作用。

2)Visual Studio 2005对于观看STL容器有很棒的支持。这适用于嵌套容器,但这仅适用于STL,并且在将STL容器放入Boost容器时不起作用。

3)编写您自己的'打印'功能(或方法),您可以在调试过程中打印特定项目,并在GDB打印项目时使用'call'。请注意,如果你的打印函数没有在代码中的任何地方被调用,g ++将会执行死代码消除,并且GDB将找不到“打印”函数(你会得到一条消息说函数是内联的)。因此,与-fkeep内联函数

6

在〜/中加入以下内容。gdbinit

define print_vector 
    if $argc == 2 
     set $elem = $arg0.size() 
     if $arg1 >= $arg0.size() 
      printf "Error, %s.size() = %d, printing last element:\n", "$arg0", $arg0.size() 
      set $elem = $arg1 -1 
     end 
     print *($arg0._M_impl._M_start + $elem)@1 
    else 
     print *($arg0._M_impl._M_start)@$arg0.size() 
    end 
end 

document print_vector 
Display vector contents 
Usage: print_vector VECTOR_NAME INDEX 
VECTOR_NAME is the name of the vector 
INDEX is an optional argument specifying the element to display 
end 

重新启动的gdb(或源〜/ .gdbinit)后,显示出这样

gdb) help print_vector 
Display vector contents 
Usage: print_vector VECTOR_NAME INDEX 
VECTOR_NAME is the name of the vector 
INDEX is an optional argument specifying the element to display 

实施例的使用关联的帮助:

(gdb) print_vector videoconfig_.entries 0 
$32 = {{subChannelId = 177 '\261', sourceId = 0 '\000', hasH264PayloadInfo = false, bitrate = 0,  payloadType = 68 'D', maxFs = 0, maxMbps = 0, maxFps = 134, encoder = 0 '\000', temporalLayers = 0 '\000'}}