tags:

views:

191

answers:

4

Can you do something like this with a macro in C?

#define SUPERMACRO(X,Y) #define X Y

then

SUPERMACRO(A,B) expands to #define A B

I have a feeling not because the preprocessor only does one pass.

EDIT

Official gcc only. No third-party tools please.

+2  A: 

Sorry, you cannot. You can call other macros in macros but not define new ones.

Tuomas Pelkonen
how about if you did 2 passes of the pre processor
pm100
The syntax is not valid. # is kind of a reserved character in macros. # must be followed by a macro parameter to be valid. This will 'stringify' the parameter.
Tuomas Pelkonen
+2  A: 

Macros can't expand into preprocessing directives. From C99 6.10.3.4/3 "Rescanning and further replacement":

The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one,

Michael Burr
+1  A: 

No. The order of operations is such that all preprocessor directives are recognized before any macro expansion is done; thus, if a macro expands into something that looks like a preprocessor directive, it won't be recognized as such, but will rather be interpreted as (erroneous) C source text.

John Bode
+1  A: 

You cannot define macros in other macros, but you can call a macro from your macro, which can get you essentially the same results.

#define B(x) do {printf("%d", (x)) }while(0)
#define A(x) B(x)

so, A(y) is expanded to do {printf("%d", (y)) }while(0)

WhirlWind