Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C preprocessor Macro defining Macro

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.

Official gcc only. No third-party tools please.

like image 825
Mike Avatar asked Mar 11 '10 22:03

Mike


People also ask

Which preprocessor is used define macros?

The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.

Can we define macro inside a macro?

No, because C 2011 [N1570] 6.10. 3.4 3 says, about macro replacement, “The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one,…” Show activity on this post.

Can I #define in a macro?

(2) However, you cannot define a macro of a macro like #define INCLUDE #define STDH include <stdio. h> .

Which preprocessor command is used for macro definition in C?

This C tutorial explains how to use the #define preprocessor directive in the C language.


2 Answers

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,

like image 197
Michael Burr Avatar answered Sep 21 '22 15:09

Michael Burr


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)

like image 39
WhirlWind Avatar answered Sep 20 '22 15:09

WhirlWind