Saturday, February 25, 2012

How to get function's name from function's pointer in C? (GCC extensions)

In my previous post I described how to get function's name from function's pointer in C under Windows for debug purposes.

In GCC you may use backtrace_symbolos declared in <execinfo.h>. An example looks like:

#include <execinfo.h>

void *pfunc = ...; /* pointer to some function */

void *buffer[1] = {pfunc};
char **strings = backtrace_symbols(buffer, 1);
if (strings == NULL) {
  perror("backtrace_symbols");
} else {
  printf("%s\n", strings[0]);
  free(strings);
}

You have to link with -rdynamic flag. The output looks like:

./a.out(myfunc+0) [0x400987]

If function is static name is omitted.

I recommend to use the things like this for debugging only.

No comments:

Post a Comment