R – substitute __func__ into an identifier name in a C macro

cmacros

I'd like to write a C macro which takes this:

int foo() {
  MY_MACRO
}

and expands it to this:

int foo() {
  _macro_var_foo++;
}

I've found that I can't use __func__, because that doesn't actually get expanded in the macro; it's treated by the preprocessor like a variable.

Is there some way to get this to work?

Best Answer

The preprocessor doesn't know about functions, just source files and line numbers. At that stage it's not performing syntactical analysis, just textual analysis and substitutions. That's why __func__ is a magical variable instead of a magical macro like __FILE__ and __LINE__.