kaspersky
kaspersky

Reputation: 4117

How to use __func__ in macros

I am trying to create a macro that will modify a field in a data structure based on the function name in which the macro is invoked, see below:

#define REGISTER(func_name) data.func_name##_n++

struct data
{
    int func_name_n;
} data;

void func_name(void)
{
    REGISTER(func_name);
}

int main(void)
{
    func_name();
    return 0; 
}

I want to use the __func__ macro, so the user could just type REGISTER and the function name will be passed automatically:

#define REGISTER(func_name) data.func_name##_n++
#define REGISTER_WRAP REGISTER(__func__)

REGISTER_WRAP;

but I get the following error:

error: ‘struct data’ has no member named ‘__func___n’

Is there a way to use __func__ in the macro and obtain the desired result?

Upvotes: 0

Views: 1300

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96579

__func__ is not a macro. It's an implicitly created variable:

static const char __func__[] = "function-name";

You can't use its value at compile time.

Upvotes: 2

Related Questions