如何在C中自动打印结构值(如gdb ptype)?
这个问题在我脑海里停留了很长时间。 我们知道,我们在调试时可以很方便地打印GDB中的数据结构,就像gdb ptype命令一样,它可以输出结构体的所有字段值。我知道GDB使用bfd库来读取目标文件中的符号信息。 我的问题是:如果我想在我的C源代码中执行此操作,该怎么办?因为我不想一一打印结构的每个字段。有没有现有的库可以解决这个问题? 我认为该库不仅可以满足我的要求,对于许多其他程序员在编写 C/C++ 代码时也非常有用。
This question stay in my head for a long time.
As we know, we can easily print data structure in GDB when we debugging, like gdb ptype command, it can output all field value of structure. I know GDB use bfd library to read symbolic information in object file.
My question is: if I want to do this in my C source code, how to do? because I don't want to printf each field of structure one by one. Is there have any exist library to solve this issue?
I think that library will not only meets my requirement, it will be very useful for many others programmers when writing C/C++ code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于C 来说,这样的库是不可能存在的。
您可以做的是编写一种编译器类型的工具,该工具采用某种语言的 struct 描述,并生成带有 C 语言的 struct 声明的头文件和带有打印的源文件代码。此类工具确实存在(例如 protobuf-c),但它们主要面向高效的二进制序列化,而不是人类可读的 C 数据表示。
As far as C is concerned, such a library cannot exist.
What you can do is write a compiler kind of tool that takes a
struct
description in some language and generates a header file withstruct
declarations in C, and a source file with printing code. Such tools do exist (e.g. protobuf-c), but they are mostly geared towards efficient binary serialization, not human-readable representation of C data.我认为没有为 C 构建的工具被广泛使用。不过,你可以尝试编写一个函数来承担这个负担,并在需要时调用它。我知道函数无法打印各种结构,并且您必须为每种类型的结构构建每个结构,但这仍然是一个比仅坚持旧规则(每次都编写)更好的主意。
I dont think there are such tools built for C which are widely used. However, you can try to write a function to take the burden and call it when needed. I know a function cannot print all sorts of structure and you've got to build each for each type of struct but it still is a better idea than to just stick to the old rule, write each time.