2008-10-31 65 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'}}