簡體   English   中英

如何在 GDB 中打印 C++ 向量的元素?

[英]How do I print the elements of a C++ vector in GDB?

我想檢查 GDB 中std::vector的內容,我該怎么做? 為簡單起見,假設它是std::vector<int>

使用 GCC 4.1.2,要打印整個名為 myVector 的 std::vector<int>,請執行以下操作:

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 

打印從指針 P 開始的數組的 N 個元素的 GDB 命令是:

print P@N

或者,以簡短的形式(對於標准的 .gdbinit):

p P@N

要查看向量 std::vector 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,我認為)。

將以下內容放入 ~/.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(或source ~/.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'}}

在調試時“觀察”STL 容器有點問題。 這是我過去使用過的 3 種不同的解決方案,它們都不是完美的。

1) 使用來自http://clith.com/gdb_stl_utils/ 的GDB 腳本 這些腳本允許您打印幾乎所有 STL 容器的內容。 問題是這對嵌套容器(如一組集合)不起作用。

2) Visual Studio 2005 非常支持觀看 STL 容器。 這適用於嵌套容器,但這僅適用於 STL 的實現,如果您將 STL 容器放入 Boost 容器中,則不起作用。

3) 為調試時要打印的特定項目編寫自己的“打印”函數(或方法),並在 GDB 中使用“調用”打印項目。 請注意,如果您的打印函數沒有在代碼中的任何地方被調用,g++ 將執行死代碼消除,並且 GDB 將找不到“打印”函數(您將收到一條消息,指出該函數已內聯)。 所以用 -fkeep-inline-functions 編譯

聚會有點晚了,所以下次我做這個搜索時主要是提醒我!

我已經能夠使用:

p/x *(&vec[2])@4

vec[2]開始從vec打印 4 個元素(作為十六進制)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM