#ifdef 里面#define

问题描述 投票:0回答:6

我正在尝试写这样的东西:

#define COV_ON(x) \
                #ifdef COVERAGE_TOOL \
                    _Pragma (COVERAGE #x)
                #endif

有没有办法像这样定义

COV_ON
?我知道我上面所做的事情是错误的,因为我不能在 #define 中包含
#ifdef
。 (
#
不是
#define
中允许使用的字符)。 那么有什么解决办法吗?

c c-preprocessor
6个回答
115
投票

不可能。 反过来做:

#ifdef COVERAGE_TOOL
#define COV_ON(x) _Pragma (COVERAGE #x)
#else
#define COV_ON(x)
#endif

23
投票

只需转动它:

#ifdef COVERAGE_TOOL
#define COV_ON(x) _Pragma (COVERAGE #x)
#else
#define COV_ON(x) /* foo */
#endif

21
投票

这是一个老问题,但需要一个最新的答案。

您可以选择性地定义一个

__VA_ARGS__
宏来执行相同的操作,而不是在宏中使用内联 ifdef

#ifdef COVERAGE_TOOL
#define IF_COVERAGE_TOOL(...) __VA_ARGS__
#else
#define IF_COVERAGE_TOOL(...)
#endif
#define COV_ON(x) IF_COVERAGE_TOOL( _Pragma (COVERAGE #x) )

这与 ifdef 具有类似的功能,只不过您使用括号来描述开始和结束(大多数 IDE 都没有代码折叠问题)。虽然您仍然可以在上下文中使用

#define
#ifdef
,但
#include
是不允许。 为了获得类似
#else
的内联功能,你可以像这样定义相应的宏:

//#define FOO
#ifdef FOO
#define IF_FOO(...) __VA_ARGS__ 
#define NO_FOO(...)
#else
#define IF_FOO(...)
#define NO_FOO(...) __VA_ARGS__
#endif

IF_FOO(
  int foo = FOO;
)
NO_FOO(
  int foo = 5;
)

只有

NO_FOO()/IF_FOO
之一会生成代码。

好吧,这是一个方便的技巧,但是我们可以让它比#ifdefs更有用吗?也许布尔逻辑和配置? 让我们设置一些真值表(和几个辅助宏)。

#define PASTE_(x,y) x##y
#define PASTE(x,y) PASTE_(x,y)
#define PASTE3_(x,y,z) x##y##z
#define PASTE3(x,y,z) PASTE3_(x,y,z)
#define Y(...) __VA_ARGS__
#define N(...)
#define IF(x) x //alternate method similar to IFNOT()

#define NOT_N Y
#define NOT_Y N
#define IF_NOT(x) PASTE(NOT_,x)
#define NOT(x) PASTE(NOT_,x)

#define N_OR_N N
#define N_OR_Y Y
#define Y_OR_N Y
#define Y_OR_Y Y
#define OR(x,y) PASTE3(x,_OR_,y)

#define N_AND_N N
#define N_AND_Y N
#define Y_AND_N N
#define Y_AND_Y Y
#define AND(x,y) PASTE3(x,_AND_,y)

#define N_XOR_N N
#define N_XOR_Y Y
#define Y_XOR_N Y
#define Y_XOR_Y N
#define XOR(x,y) PASTE3(x,_XOR_,y)

#define N_NOR_N Y
#define N_NOR_Y N
#define Y_NOR_N N
#define Y_NOR_Y N
#define NOR(x,y) PASTE3(x,_NOR_,y)

#define N_NAND_N Y
#define N_NAND_Y Y
#define Y_NAND_N Y
#define Y_NAND_Y N
#define NAND(x,y) PASTE3(x,_NAND_,y)

#define N_XNOR_N Y
#define N_XNOR_Y N
#define Y_XNOR_N N
#define Y_XNOR_Y Y
#define XNOR(x,y) PASTE3(x,_XNOR_,y)

#define IF2(x,y,z) PASTE3(x,y,z)

配置.h

#define FOO Y #define BAR N #define BAZ Y

代码.c

AND(FOO,BAR)(/*do stuff if both FOO and BAR are enabled*/) IF2(FOO,_AND_,BAR)( /*do stuff if both FOO and BAR are enabled*/ ) OR(BAZ,AND(FOO,BAR))( /*do stuff if both FOO and BAR are enabled or BAZ is enabled*/ )



6
投票


6
投票
#ifdef

#define
:

#ifdef COVERAGE_TOOL # define COV_ON(x) _Pragma (COVERAGE #x) #else # define COV_ON(x) #endif



3
投票

#ifdef COVERAGE_TOOL \ #define COV_ON(x) \ etc. #endif

	
© www.soinside.com 2019 - 2024. All rights reserved.