簡體   English   中英

如何在C預處理器中使用#if在#define中?

[英]How to use #if inside #define in the C preprocessor?

我想編寫一個宏,根據其參數的布爾值吐出代碼。 所以說DEF_CONST(true)應該擴展為const ,而DEF_CONST(false)應該擴展為DEF_CONST(false)

顯然,以下方法不起作用,因為我們不能在#defines中使用另一個預處理器:

#define DEF_CONST(b_const) \
#if (b_const) \
  const \
#endif

您可以使用宏標記連接來模擬條件,如下所示:

#define DEF_CONST(b_const) DEF_CONST_##b_const
#define DEF_CONST_true const
#define DEF_CONST_false

然后,

/* OK */
DEF_CONST(true)  int x;  /* expands to const int x */
DEF_CONST(false) int y;  /* expands to int y */

/* NOT OK */
bool bSomeBool = true;       // technically not C :)
DEF_CONST(bSomeBool) int z;  /* error: preprocessor does not know the value
                                of bSomeBool */

另外,允許將宏參數傳遞給DEF_CONST本身(正如GMan和其他人正確指出的那樣):

#define DEF_CONST2(b_const) DEF_CONST_##b_const
#define DEF_CONST(b_const) DEF_CONST2(b_const)
#define DEF_CONST_true const
#define DEF_CONST_false

#define b true
#define c false

/* OK */
DEF_CONST(b) int x;     /* expands to const int x */
DEF_CONST(c) int y;     /* expands to int y */
DEF_CONST(true) int z;  /* expands to const int z */

您可能還會考慮更簡單(盡管可能不太靈活):

#if b_const
# define DEF_CONST const
#else /*b_const*/
# define DEF_CONST
#endif /*b_const*/

把它作為一個paramterised宏有點奇怪。

為什么不做這樣的事情:

#ifdef USE_CONST
    #define MYCONST const
#else
    #define MYCONST
#endif

然后你可以寫這樣的代碼:

MYCONST int x = 1;
MYCONST char* foo = "bar";

如果您使用定義的USE_CONST編譯(例如,通常在makefile或編譯器選項中使用-DUSE_CONST ),那么它將使用consts,否則不會。

編輯:其實我看到弗拉德在他的答案結束時覆蓋了那個選項,所以給他+1 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM