繁体   English   中英

如何根据宏值定义宏?

[英]How to define macro bases on macro value?

我有宏:

#if defined DEBUG  &&  DEBUG
#  define D(...) printf(__VA_ARGS__)
#else
#  define D(...)
#endif

DEBUG具有TRUE值时,该选项实际上不执行任何操作。

但是现在我想提供TYPE东西。 将显示调试类型:

D( 1, "some string" );
D( 2, "another thing" );

有没有一种方法可以定义这样的宏,即当DEBUG2时对D(1,..)不执行任何操作D(1,..)并为D(2,...)打印调试消息,反之则在1时进行DEBUG

我想这样:

#if defined DEBUG  &&  DEBUG
#  define D(type,...) if DEBUG&type THEN printf(__VA_ARGS__) else do nothing
#else
#  define D(...)
#endif

好吧,它不会在预处理时得到真正的评估,但是如果类型是编译时常数,那么仍然是编译类型。

#define D(type, ...) (void)((type & DEBUG) && fprintf(stderr, __VA_ARGS__))

以上至少需要C99。

你可以这样做;

#if defined DEBUG  
#  define P1(...) 
#  define P2(...) printf(__VA_ARGS__)
#  define D(n, ...) P##n(__VA_ARGS__)
#else
#  define D(...)
#endif

main()
{
    D(1, "Test");
    D(2, "Test2");
}

这不能解决问题,但请让我更进一步。 也许对某人有用:

#define _CAT(a, ...) a ## __VA_ARGS__

#define CHECK(...) SECOND(__VA_ARGS__, 0)
#define SECOND(x, n, ...) n

#define _NOT_0 _TRUE()
#define _TRUE() ~, 1

#define BOOL(x) NOT(NOT(x))
#define NOT(x) CHECK(_CAT(_NOT_, x))

#define IF(cond) _IF(BOOL(cond))
#define _IF(cond) _CAT(_IF_, cond)
#define _IF_1(...) __VA_ARGS__
#define _IF_0(...)

IF(1)(printf("YES\n");)
IF(0)(printf("NO\n");)

技巧的链接: 第一第二 第二个链接更有趣,因为它描述了逐步进行的操作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM