camino
camino

Reputation: 10574

how to use #if,#else,#endif... inside c macro

 #include < iostream >  

 #define MY_CHK_DEF(flag) \
 #ifdef (flag) \
    std::cout<<#flag<<std::endl; \
 #else \
    std::cout<<#flag<<" ,flag not define"<<std::endl; \
 #endif 


 int main()
 {
    MY_CHK_DEF(FLAG_1);
    MY_CHK_DEF(FLAG_2);
    MY_CHK_DEF(FLAG_3);
    ...  
 }

complier report:

main.cpp:3:24: error: '#' is not followed by a macro parameter

any ideas?

Thanks

Upvotes: 10

Views: 13411

Answers (4)

Urkle
Urkle

Reputation: 1678

You actually can do this if you use BOOST processor header lib.. it provides a BOOST_PP_IF macro allow this type of decisions.

http://www.boost.org/doc/libs/1_53_0/libs/preprocessor/doc/ref/if.html

Upvotes: 1

Roman A. Taycher
Roman A. Taycher

Reputation: 19477

You have to do it the other way round(defining the macro for each #if/#ifdef/#else condition(if you nest you have to put a definition on each branch). You probably should define it at every logical branch or it will fail to compile when you try to adjust a rarely adjusted flag. You can #define noops like this. Note to be careful not to wrap expressions with side effects into #define 'd macros that reduce to a noop when the debug flag is on, or your program may not work right.

 #define N(x) 

 #include < iostream > 

 #ifdef (flag) 
 #define MY_CHK_DEF(flag) 
    std::cout<<#flag<<std::endl; 
 #else 
 #define MY_CHK_DEF(flag) \
    std::cout<<#flag<<" ,flag not define"<<std::endl;
 #endif 


 int main()
 {
    MY_CHK_DEF(FLAG_1);
    MY_CHK_DEF(FLAG_2);
    MY_CHK_DEF(FLAG_3);
    ...  
 }

Upvotes: 6

SF.
SF.

Reputation: 14029

C preprocessor is single-pass and #define creates a pretty dumb replacement that isn't further processed - your MY_CHK_DEF(flag) macro inserts the #if statement inline into preprocessed code that is interpreted by C compiler and not valid C.

You can either rephrase it to be one-pass, or if you can't, run through preprocessor twice, manually - once through cpp -P and the second time through normal compilation process.

Upvotes: 2

TonyK
TonyK

Reputation: 17114

You can't do it. #if, #else, and #endif must be the first tokens on the logical line. Your definition is just one logical line, so it doesn't work,

Upvotes: 8

Related Questions