In C/C++, we have the __FUNCTION__
macro which is replaced with a string, holding the name of the current function. But what if I want the function's identifier? That is, not a string, but something I could use as a token to create other identifiers, e.g., if we have
#define MAGIC /* ... */
#define MORE_MAGIC MAGIC ## _bar
void foo() {
printf("%s\n",__FUNCTION__);
MORE_MAGIC();
}
void foo_bar() {
printf("%s\n",__FUNCTION__);
}
void baz() {
printf("%s\n",__FUNCTION__);
MORE_MAGIC();
}
void baz_bar() {
printf("%s\n",__FUNCTION__);
}
int main() {
foo();
}
should print
foo
foo_bar
baz
baz_bar
Notes:
(C++11) The predefined identifier __func__ is implicitly defined as a string that contains the unqualified and unadorned name of the enclosing function.
static const char __func__[] = “function-name”; appeared, where function-name is the name of the lexically-enclosing function. “ It means that the C compiler implicitly adds __func__ in every function so that it can be used in that function to get the function name.
Unfortunately you can't. Because you can not unstringify a macro[1].
In other words, you can not remove quotes around the string that generated by __FUNCTION__
and contact it by _bar
.
If it's compile-time you want, and for a simple case like your, it might be possible with preprocessor macros and the concatenation operator ##
. Maybe something like
#define MORE_MAGIC(f) f##_bar
...
void foo_bar()
{
}
void foo()
{
MORE_MAGIC(foo)();
}
It's not possible to get the name foo
automatically though, it has to be explicitly named in the macro "call".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With