GDB使用gdb-stl-views打印STL容器元素

简介

使用gdb调试C++程序时,无法使用命令p 变量名输出STL容器的元素数据。例如有一个std::vector datas变量, 执行p datas,输出如下:

(gdb) p datas     
$2 = {
  <std::_Vector_base<int, std::allocator<int> >> = {
    _M_impl = {
      <std::allocator<int>> = {
        <__gnu_cxx::new_allocator<int>> = {<No data fields>}, <No data fields>}, 
      members of std::_Vector_base<int, std::allocator<int> >::_Vector_impl: 
      _M_start = 0x606010, 
      _M_finish = 0x60601c, 
      _M_end_of_storage = 0x606020
    }
  }, <No data fields>}

可以使用一个名为gdb-stl-views的小工具,下载完成后,将其改名为.gdbinit并放置到home目录下,然后再执行输出STL容器内容的新命令,对于std::vector,执行pvector datas,输出信息如下:

(gdb) pvector datas
elem[0]: $3 = 1
elem[1]: $4 = 2
elem[2]: $5 = 3
Vector size = 3
Vector capacity = 4
Element type = std::_Vector_base<int, std::allocator<int> >::pointer

新命令

对于STL的各种容器,输出其元素的命令如下:

容器类型 GDB 命令
std::vector pvector
std::list plist
std::map pmap
std::multimap pmap
std::set pset
std::multiset pset
std::deque pdeque
std::stack pstack
std::queue pqueue
std::priority_queue ppqueue

对于std::vector,输出命令为pvector 变量名,而对于std::map,输出命令为pmap 变量名 键类型 值类型,就需要给出除变量之外的其他信息。

要查看某一个命令的所有用法,可以使用命令help 命令。例如使用help pmap,可以得到如下信息:

(gdb) help pmap
	Prints std::map<TLeft and TRight> or std::multimap<TLeft and TRight> information. Works for std::multimap as well.
	Syntax: pmap <map> <TtypeLeft> <TypeRight> <valLeft> <valRight>: Prints map size, if T defined all elements or just element(s) with val(s)
	Examples:
	pmap m - prints map size and definition
	pmap m int int - prints all elements and map size
	pmap m int int 20 - prints the element(s) with left-value = 20 (if any) and map size
	pmap m int int 20 200 - prints the element(s) with left-value = 20 and right-value = 200 (if any) and map size

参考

GDB中查看STL容器类的内容
在linux用gdb查看stl中的数据结构

你可能感兴趣的:(Linux,C/C++,GDB,STL容器,打印输出)