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"
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With