How to find the name of the current function at runtime?

demoncodemonkey picture demoncodemonkey · Mar 24, 2009 · Viewed 51k times · Source

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.

Answer

Assaf Lavie picture Assaf Lavie · Mar 24, 2009

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()"
}