如何在运行时找到当前函数的名称? [英] How to find the name of the current function at runtime?

查看:141
本文介绍了如何在运行时找到当前函数的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过多年使用大丑陋的MFC ASSERT宏后,我终于决定放弃它并创建最终的ASSERT宏。



我很高兴得到文件和行号,甚至失败的表达式。我可以显示一个带有这些和中止/重试/取消按钮的消息框。



当我按Retry时,VS调试器跳转到包含ASSERT调用的行与其它ASSERT函数类似的反汇编)。



但是真正酷的是显示失败的函数的名称。

>

然后我可以决定是否调试它,而不试图猜测它的文件名是什么函数。



如果我有以下函数:

  int CMainFrame :: OnCreate(LPCREATESTRUCT lpCreateStruct)
{
ASSERT (lpCreateStruct-> cx> 0);
...
}

然后当ASSERT触发时,消息框显示如下:

  Function = CMainFrame :: OnCreate 

那么,在运行时查找当前函数名称的最简单的方法是什么? $ p

它不应该使用MFC或.NET框架,即使我使用这两个。

它应该尽可能的便携。

解决方案

宏可以包含 __ FUNCTION __ 宏。
毫无疑问,编译时会将函数名 插入到扩展代码中,但每次调用宏的函数名称都是正确的。所以它似乎是在运行时发生的)



例如

  #define THROW_IF(val)if(val)throw在__FUNCTION__中的错误

int foo()
{
int a = 0;
THROW_IF(a> 0); // will throwerror in foo()
}


After years of using the big ugly MFC ASSERT macro, I have finally decided to ditch it and create the ultimate ASSERT macro.

I am fine with getting the file and line number, and even the expression that failed. I can display a messagebox with these in, and Abort/Retry/Cancel buttons.

And when I press Retry the VS debugger jumps to the line containing the ASSERT call (as opposed to the disassembly somewhere like some other ASSERT functions). So it's all pretty much working.

But what would be really cool would be to display the name of the function that failed.

Then I can decide whether to debug it without trying to guess what function it's in from the filename.

e.g. if I have the following function:

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
   ASSERT(lpCreateStruct->cx > 0);
   ...
}

Then when the ASSERT fires, the messagebox would show something like:

Function = CMainFrame::OnCreate

So, what's the simplest way of finding out the current function name, at runtime?

It should not use MFC or the .NET framework, even though I do use both of these.
It should be as portable as possible.

解决方案

Your macro can contain the __FUNCTION__ macro. Make no mistake, the function name will be inserted into the expanded code at compile time, but it will be the correct function name for each call to your macro. So it "seems like" it happens in run-time ;)

e.g.

#define THROW_IF(val) if (val) throw "error in " __FUNCTION__

int foo()
{
    int a = 0;
    THROW_IF(a > 0); // will throw "error in foo()"
}

这篇关于如何在运行时找到当前函数的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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