tags:

views:

744

answers:

4

I have been using PRETTY_FUNCTION to output the current function name, however I have reimplemented some functions and would like to find out which functions are calling them.

In C++ how can I get the function name of the calling routine?

+4  A: 

Here are two options:

  1. You can get a full stacktrace (including the name, module, and offset of the calling function) with recent versions of glibc with the GNU backtrace functions. See my answer here for the details. This is probably the easiest thing.

  2. If that isn't exactly what you're looking for, then you might try libunwind, but it's going to involve more work.

Keep in mind that this isn't something you can know statically (as with PRETTY_FUNCTION); you actually have to walk the stack to figure out what function called you. So this isn't something that's really worth doing in ordinary debug printfs. If you want to do more serious debugging or analysis, though, then this might be useful for you.

tgamblin
A: 

You probably want the names of all functions that potentially could call them. This is basically a set of edges in the call graph. Doxygen can generate the call graph, and then it's simply a matter of looking at the incoming edges of your functions node.

MSalters
This doesn't tell you who actually called you. It only tells you who could've called you.
tgamblin
And what about libraries. It does not tell you what application functions may call you.
Martin York
A: 

In the firs approximation, just grep the codebase for the function names. Then comes Doxygen, and then dynamic logging (both discussed by others).

Arkadiy
+2  A: 

Here is a solution you can often use. It has the advantage of requiring no changes to the actual function code (no adding calls to stackwalk functions, changing parameters to pass in function names, or linking to extra libraries.). To get it working, you simply need to use a bit of preprocessor magic:

// orignal function name was 'FunctionName'
void FunctionNameReal(...)
{
  // Do Something
}

#undef FunctionName
#define FunctionName printf("Calling FunctionName from %s\n",__FUNCTION__);FunctionNameReal

You must rename your function temporarily, but see the note below for more suggestions. This will result in a printf() statement at each point of calling the function. Obviously, you have to make some arrangements if you are calling a member function, or need to capture the return value (Like pass the function call and __FUNCTION__ to a custom function that returns the same type...), but the basic technique is the same. You might want to use __LINE__ and __FILE__ or some other preprocessor macros depending on which compiler you have. (This example is specifically for MS VC++, but probably works in others.)

Also, you might want to put something like this in your header surrounded by #ifdef guards to conditionally turn it on, which can handle renaming the actual function for you as well.

Aaron