user1393608
user1393608

Reputation: 1349

How to print macro name in c or c++

How to print macro name in c or c++ eg:

#define APINAME abc
#define PRINTAPI(x) printf("x")

I want to print PRINTAPI(APINAME) and not "abc"

Upvotes: 9

Views: 21353

Answers (2)

masoud
masoud

Reputation: 56479

Macros are pre-processors and they will be replaced by their associated statement before compiling the code. So, you have no chance to have the macro names in run-time. But, you can generate the string name in compile-time:

#define APINAME abc
#define PRINTAPI(x) std::cout << #x << std::endl;

int main()
{
    PRINTAPI(APINAME);
}

Output

APINAME

In macros the operator # makes the input parameter to a string literal (stringify)

Upvotes: 13

Mats Petersson
Mats Petersson

Reputation: 129344

Since macros disappear when the preprocessor is doing it's work, which happens before the compiler is called, the APINAME will not exist anywhere in the source code for the compiler to deal with. The only solution is to come up with some sort of connection between the two in some other way, e.g.

 struct foo{
    const char *name;
    const char *val;
 } myvar = { "APINAME", APINAME };

With a macro, you can do this in as a one-liner:

#define APINAME "abc"
#define APINAME_VAR(x, y) struct foo x = { #y, y }

APINAME_VAR(myvar, APINAME)

or

 cout << "APINAME=" << APINAME << endl

 printf("APINAME=%s\n", APINAME);

Or, in the case of your macro:

 #define PRINTAPI printf("%s=%s\n", #APINAME, APINAME)

will print APINAME=abc

Upvotes: 4

Related Questions