Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I obtain the identifier of the current function?

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:

  • I'm interested in preprocessing-time only.
  • I would rather not replace my function definitions with a preprocessor call - although I know that would probably work.
like image 452
einpoklum Avatar asked Mar 11 '14 08:03

einpoklum


People also ask

What is__ func__ in c++?

(C++11) The predefined identifier __func__ is implicitly defined as a string that contains the unqualified and unadorned name of the enclosing function.

What does __ func __ return?

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.


2 Answers

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.

like image 119
masoud Avatar answered Nov 08 '22 20:11

masoud


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".

like image 34
Some programmer dude Avatar answered Nov 08 '22 20:11

Some programmer dude