How to use # if, # else, # endif ... inside a 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); ... } 

error reporting:

main.cpp: 3: 24: error: "#" is not accompanied by a macro parameter

any ideas?

thanks

+6
source share
4 answers

You cannot do this. #if, #else and #endif should be the first tokens in the logical line. Your definition is just one logical line, so it doesnโ€™t work,

+7
source

You should do this in the reverse order (by defining a macro for each if if # / ifdef / # else condition (if you should put a definition in each branch in the socket). You should probably define it with every boolean If you try to configure a rarely adjusted flag, you wonโ€™t be able to compile it. You can #define noops like this. Note that you donโ€™t wrap expressions with side effects in #define 'd macros that reduce to zero when the debugging flag is turned on, or your program may not work correctly .

  #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); ... } 
+6
source
Preprocessor

C is single-pass, and #define creates a rather dumb substitution that is not yet processed - your macro MY_CHK_DEF (flag) inserts the #if operator in a string into pre-processed code that is interpreted by the C compiler and invalid C.

You can either rephrase it as a single-pass, or, if you cannot, run the preprocessor twice, manually - once through cpp -P and a second time through the normal compilation process.

+2
source

You can actually do this if you use a BOVST processor with the lib header .. it provides the BOOST_PP_IF macro, allowing this type of solution.

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

-1
source

Source: https://habr.com/ru/post/887688/


All Articles