Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print macro name in c or c++

Tags:

c++

macros

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"

like image 777
user1393608 Avatar asked May 17 '13 12:05

user1393608


2 Answers

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)

like image 57
masoud Avatar answered Oct 06 '22 01:10

masoud


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

like image 35
Mats Petersson Avatar answered Oct 06 '22 01:10

Mats Petersson