如何在 C 宏中使用 #if,#else,#endif...
#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);
...
}
编译器报告:
main.cpp:3:24:错误:“#”后面没有跟宏参数
有什么想法吗?
谢谢
#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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你做不到。 #if、#else 和 #endif 必须是逻辑行上的第一个标记。你的定义只是一个逻辑线,所以它不起作用,
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,
您必须以相反的方式进行操作(为每个 #if/#ifdef/#else 条件定义宏(如果您嵌套,则必须在每个分支上放置一个定义)。您可能应该在每个逻辑分支或它定义它当您尝试调整很少调整的标志时,将无法编译。您可以像这样#define noops,请注意不要将具有副作用的表达式包装到#define'd宏中,这些宏在调试标志打开时会减少为noop。 ,否则你的程序可能无法正常工作。
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.
C 预处理器是单通道的,并且 #define 创建了一个非常愚蠢的替换,不会进一步处理 - 您的 MY_CHK_DEF(flag) 宏将 #if 语句内联插入到由 C 编译器解释的预处理代码中,而不是有效的 C。
您可以将其改写为一次性,或者如果不能,请手动运行预处理器两次 - 一次通过 cpp -P ,第二次通过正常编译过程。
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.如果您使用 BOOST 处理器头库,您实际上可以做到这一点。它提供了一个 BOOST_PP_IF 宏允许这种类型的决策。
http://www.boost.org/doc /libs/1_53_0/libs/preprocessor/doc/ref/if.html
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