user967007
user967007

Reputation:

c stringification and __function__

I am trying to add a c macro which compiles a local variable which is initialized to the function name..

for example.

 void foo (void)
 {
 stubmacro;
 }


 void bar (void)
 {
 stubmacro;
 }

would essentially compile as:

 void foo (void)
 {
 char*function_name="foo";
 }


 void bar (void)
 {
 char*function_name="bar";
 }

I've always had a difficult time with C preprocessor macros, especially when it comes to stringification

the macro uses the prefined FUNCTION ..

#define stubmacro char*function_name=##_FUNCTION__

Anyway, my stubmacro macro is wrong, and I' would love some help on it

Upvotes: 1

Views: 612

Answers (2)

Santosh A
Santosh A

Reputation: 5351

You can refer the below code:

#include <stdio.h>

#define stubmacro char *func = __func__;

void foo (void)
{
    stubmacro;
    printf("foo = %s\n", func);
}

void bar (void)
{
    stubmacro;
    printf("bar = %s\n", func);
}

int main(void)
{
    foo();
    bar();
    return 0;
}

The output would be:

foo = foo
bar = bar

Here __func__ is a macro that will be replaced with the function name in which it is used

Also instead using a macro for the function name you can directly print in the function like below

void foo (void)
{
    printf("foo = %s\n", __func__);
}

Upvotes: 1

Jens Gustedt
Jens Gustedt

Reputation: 78903

Just use __func__, this is a predefined string that does what you need:

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.

Upvotes: 4

Related Questions