如何显示gdb以正确显示变量? [英] How can I show gdb to show my variables properly?

查看:68
本文介绍了如何显示gdb以正确显示变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个简单的子字符串类和一个简单的数组.当我调试时,这很头疼,因为我需要多次单击才能获取某种有意义的信息.有没有一种方法可以标记我的源代码,其中包含某种配置,该配置信息表示当我打印变量a时实际上是我的意思

For example I have a simple substring class and a simple array. When I'm debugging it's a headache because I need many clicks just to get some kind of sensible information. Is there a way I can markup my source of have some kind of config that says when I print the variable a I actually mean

p *a.start@(a.end-a.start)

当我检查数组时,我希望它以上面的样式显示变量( p *arr.array@arr.pos 真是一团糟)

When I exam array I'd like it to show the variable in the style above (p *arr.array@arr.pos is a mess)

当前GDB输出

$ gdb ./a.out 
(gdb) br a.cpp:38
Breakpoint 1 at 0x128f: file a.cpp, line 38.
(gdb) r
(gdb) p a
$1 = {start = 0x555555556004 "My test string that has two parts", end = 0x555555556012 " that has two parts"}
(gdb) 

我的Source用 g ++ -g a.cpp

#include <cstdio>
struct MyString
{
    const char *start, *end;
    int size() { return end-start; }
};
template<class T>
struct MyArray
{
    int pos;
    T array[10];
    MyArray() : pos(0) {}
    void push(T val) {
        if (pos >= 10)
            return;
        array[pos++] = val;
    }
};

struct MoreComplex
{
    int val;
    MyString substring;
};

int main() {
    const char* str = "My test string that has two parts";
    MyString a{str, str+14};
    MyString b{str+20, str+27};
    MoreComplex c{5, b};
    MyArray<MyString> arr;
    arr.push(a);
    arr.push(b);

    MyArray<MoreComplex*> arr2;
    arr2.push(&c);
    puts("Breakpoint here");
    return 0;
}

推荐答案

如果您使用的是基于python的gdb版本,则可以添加自定义

If you have a python-enabled build of gdb, you can add custom pretty printers for your types.

您可以尝试将以下内容添加到.gdbinit中:

You could try adding the following to your .gdbinit:

python

class MyStringPrinter:
    "Print a MyString"

    def __init__ (self, val):
        self.val = val

    def to_string (self):
        ptr = self.val['start']
        len = self.val['end'] - ptr
        return ptr.string (length = len)

    def display_hint (self):
        return 'string'

pp = gdb.printing.RegexpCollectionPrettyPrinter("mine")
pp.add_printer('MyString', '^MyString$', MyStringPrinter)
gdb.printing.register_pretty_printer(gdb.current_objfile(), pp)

end

这将在打印 MyString 对象时为您提供此结果:

This will give you this result when printing a MyString object:

(gdb) p a
$1 = "My test string"
(gdb) p b
$2 = "has two"
(gdb) p c
$3 = {val = 5, substring = "has two"}

这篇关于如何显示gdb以正确显示变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆