gpt4 book ai didi

c++ - 如何使 C++ 类对 gdb 友好?

转载 作者:行者123 更新时间:2023-12-03 06:51:48 25 4
gpt4 key购买 nike

考虑以下示例:

std::string s = "Hello!!";

(gdb) p s
$1 = "Hello!!";
本质上,仅提供变量名称就足以显示字符串。例如,我不必输入“p s.c_str()”。
gdb 是否使用任何隐式运算符来获取显示字符串?我需要为我的类(class)做类似的事情。这是我类(class)的一个简单示例:
class MyClass {

private:
std::string _name;
};

最佳答案

你需要为你的类(class)写一个 pretty-print 。这不是您在 C++ 类中所做的事情,而是您在 gdb 中所做的事情(尽管与您的 C++ 类相匹配)。最简单的方法是通过 gdb 的 Python API(您也可以使用 Guile 语言)。
GDB 已经为大多数标准库类提供了 pretty-print ,这就是为什么你可以很容易地看到 std::string对象,一个 std::vector等。如果您键入 info pretty-printer在 gdb 中,它会告诉你它目前知道的 pretty-print ,你会注意到很多 std::something pretty-print 。
如果您使用通行证 /r对于 gdb 中的打印命令,它将打印变量而不使用任何可能的匹配它的注册 pretty-print 。用 std::string 试试这个看看如果 gdb 没有配备 pretty-print ,它将如何打印。

那么,如何编写自己的 pretty-print 呢?为此,您应该阅读 GDB's documentation关于这个话题。但是我发现通过阅读和调整一些现有的 pretty-print 可以更容易地开始,然后阅读 gdb 的文档以获取详细信息。
例如,我有一个 Coordinate在我的项目之一中上课,如下所示

class Coordinate {
private:
double x;
double y;
double z;

public:
...
}
为这个类编写一个 pretty-print 非常容易。您使用以下代码创建一个 python 文件
class CoordinatePrinter:
def __init__(self, val):
# val is the python representation of you C++ variable.
# It is a "gdb.Value" object and you can query the member
# atributes of the C++ object as below. Since the result is
# another "gdb.Value" I'am converting it to a python float
self.x = float(val['x'])
self.y = float(val['y'])
self.z = float(val['z'])

# Whatever the `to_string` method returns is what will be printed in
# gdb when this pretty-printer is used
def to_string(self):
return "Coordinate(x={:.2G}, y={:.2G}, z={:.2G})".format(self.x, self.y, self.z)



import gdb.printing
# Create a "collection" of pretty-printers
# Note that the argument passed to "RegexpCollectionPrettyPrinter" is the name of the pretty-printer and you can choose your own
pp = gdb.printing.RegexpCollectionPrettyPrinter('cppsim')
# Register a pretty-printer for the Coordinate class. The second argument is a
# regular expression and my Coordinate class is in a namespace called `cppsim`
pp.add_printer('Coordinate', '^cppsim::Coordinate$', CoordinatePrinter)
# Register our collection into GDB
gdb.printing.register_pretty_printer(gdb.current_objfile(), pp, replace=True)
现在我们需要做的就是 source gdb 中的这个 python 文件。为此,请写入您的 .gdbinit 文件 source full_path_to_your_python_file_with_pretty_printers.py当你启动 gdb 时,它会运行你的 .gdbinit文件,它将加载您的 pretty-print 。请注意,这些 pretty-print 通常也可以在使用 gdb 的 IDE 中工作。
如果您对更多示例感兴趣,我已经为 Armadillo 中的某些类创建了 pretty-print 。可用的库( vector 、矩阵和一般线性代数) here .

关于c++ - 如何使 C++ 类对 gdb 友好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63924895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com