Hello,
I was wondering if there is a way of finding which function called the current function (at runtime) in C.
I know you could use __FUNCTION__
in gcc, but is there a way without using the C preprocessor?
Probably not.
Cheers
Hello,
I was wondering if there is a way of finding which function called the current function (at runtime) in C.
I know you could use __FUNCTION__
in gcc, but is there a way without using the C preprocessor?
Probably not.
Cheers
No, there isn't. C isn't a particularly introspective language - things like the name of a function (or pieces of your call stack) simply aren't available at runtime in any sane fashion.
If, for some reason, you are looking for a lot of work for very little benefit, then you can build your programs with debug symbols, and you can write stack-walking and debug symbol lookup code. Then you might be able to find this out on the fly. But be careful, because the symbols you'll see in the debug info will be decorated with type info if you've got any C++ involved.
You've tagged this post gcc, so the relevant details ARE available, however this falls into the 'not recommended' and 'not guaranteed to be the same between compiler versions' territory.
There's no way to get a function name in the runtime. The only way is the preprocessor but it's very limited in its capabilities. In case you have debug information available, you could walk the stack and get the function names from the debugging information. This is, however, neither a robust nor a portable solution.
There are couple of GNU functions that allow you to get function addresses and names from backtrace - backtrace()
and backtrace_symbols()
, but you need to compile your binary with -rdynamic
flag
Use the __func__
identifier. The standard (section 6.4.2.2) requires that it be present for precisely this purpose:
The identifier __func__
shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration
static const char __func__[] = "function-name";
appeared, where function-name
is the name of the lexically-enclosing function.
As Steve Jessop notes in a comment, this isn't part of the preprocessor as such, but an intrinsic part of the compiler.
There may well be ways of finding out this name by walking the stack and looking at debugging symbols. Cute, but insane.