开发者

Reflection in Qt/C++

开发者 https://www.devze.com 2023-02-21 17:23 出处:网络
I just started with Qt and discovered the QMetaObject wich i开发者_运维技巧s very nice/handy in my opinion.

I just started with Qt and discovered the QMetaObject wich i开发者_运维技巧s very nice/handy in my opinion.

Now I wondered if it is possible to get information like current function name, calling function name or current stack with Qt/standard C++ or any other C++ library.

I need this for debugging/logging purposes.

In C# for example you can call MethodBase.GetCurrentMethod() to get the current method. Something like this would be really convenient.


There is a macro PRETTY_FUNCTION that returns a nice formatted function name. It is available in GCC and maybe some other compilers.


Don't think you can do that in C++. I think what you want to do is to create a logging macro which uses the predefined macros:

__FUNCTION__ __LINE__ __FILE__


There is no platform independent way of doing this. Sadly (or fortunately depending on your point of view) standard C/C++ does not include those sort of introspective capabilities.

There's discussion of various methods of obtaining a stack trace below and elsewhere on SO.

How can one grab a stack trace in C?

You will likely require debug symbol information to get any meaningful stack trace which you may not want to install on a customer's system.

If you really want to know the stack for a log entry on Windows without having symbolic information installed then you could write a small mini dump file (MiniDumpWriteDump). This could be saved on a customer's system without symbols and then analysed on a developer's system with the .pdb symbol for that build. This will also show local variable values and optionally you can include all process data (which makes the mini dump files huge). More information below and elsewhere on the interweb.

http://blogs.msdn.com/b/joshpoley/archive/2008/05/19/prolific-usage-of-minidumpwritedump-automating-crash-dump-analysis-part-0.aspx


You can enable RTTI in your compiler if you absolutely want to do this kind of stuff (and your compiler supports it). But in the original design of the C++ standard (pre 98) does not define any "meta" data in the runtime.

http://en.wikipedia.org/wiki/Run-time_type_information

If it is purely for logging use the macros defined by your compiler (like FILE and LINE ). If you want to do more advanced stuff in the runtime I think making your own "metadata" system might be a better plan ( or looking for an existing one on the net).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号