簡體   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