Reputation: 1922
This will print "foo\nbar\n".
#include <stdio.h>
int main(void) {
#define STRINGX(a) #a
#define STRING(a) STRINGX(a)
#define FOO foo
#define FOO_STR STRING(FOO)
printf("%s\n", FOO_STR);
#undef FOO
#define FOO bar
printf("%s\n", FOO_STR);
return 0;
}
However, suppose I wanted to save the definition of FOO_STR
, regardless of subsequent re-definitions, "foo\nfoo\n"? Is it possible to get the macro expansion of to be immediately at the place of definition?
Edit: The reason I want to do this is I have a header that I include multiple times, passing macros as arguments; it would simplify testing if I could duplicate FOO
at the first time I included it.
Upvotes: 0
Views: 86
Reputation: 67594
You are making a very important mistake. Macros are expanded textually and textually (actually at the token level) replaced. Preprocessor does not understand C language.
Macros like functions are not functions and are not "executed".
So something you want to archive is not possible as it requires C language constructs to remember some intermediate values.
My advice is : use as less macros as possible. And remember - macros are not C language and are expanded before the actual compilation.
Upvotes: 1
Reputation: 241811
That's not possible. The C preprocessor has no concept of "immediate expansion". Macro definitions are never expanded until use, and consequently there is no way to "save" the current value of a macro except to expand it:
static const char* foo_old_val = FOO_STR;
#undef FOO
#define FOO bar
printf("%s\n", foo_old_val);
Upvotes: 2