how to print structure value(like gdb ptype) automatically in C?

不打扰是莪最后的温柔 提交于 2019-12-22 09:01:04

问题


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.


回答1:


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 with struct 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.




回答2:


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.



来源:https://stackoverflow.com/questions/7466511/how-to-print-structure-valuelike-gdb-ptype-automatically-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!