【问题标题】:Preprocessor check if multiple defines are not defined预处理器检查是否未定义多个定义
【发布时间】:2013-06-18 17:18:07
【问题描述】:

我在标题中选择了一些用户可编辑的#defines,因此我随后希望检查这些定义是否存在,以防用户完全删除它们,例如

#if defined MANUF && defined SERIAL && defined MODEL
    // All defined OK so do nothing
#else
    #error "User is stoopid!"
#endif

这工作得很好,但是我想知道是否有更好的方法来检查多个定义是否到位......例如:

#ifn defined MANUF || defined SERIAL ||.... // note the n in #ifn

或许

#if !defined MANUF || !defined SERIAL ||....

消除对空 #if 部分的需要。

【问题讨论】:

  • 仅供参考:defined 是一个像函数一样被调用的运算符(就像 sizeof 一样。所以如果你像函数一样调用它,你的例子就可以正常工作。另外 - 你可以使用大多数预处理器语句中的逻辑运算符(==!=!||&&)也是如此。
  • 布尔代数的一个通用原理,可以将!(x && y)替换为(!x || !y)en.wikipedia.org/wiki/De_Morgan%27s_laws

标签: c c-preprocessor


【解决方案1】:

FWIW,@SergeyL 的回答很棒,但这里有一个用于测试的轻微变体。注意逻辑或到逻辑与的变化。

main.c 有一个这样的主包装器:

#if !defined(TEST_SPI) && !defined(TEST_SERIAL) && !defined(TEST_USB)
int main(int argc, char *argv[]) {
  // the true main() routine.
}

spi.c、serial.c 和 usb.c 具有各自测试代码的主要包装器,如下所示:

#ifdef TEST_USB
int main(int argc, char *argv[]) {
  // the  main() routine for testing the usb code.
}

config.h 包含在所有 c 文件中的条目如下:

// Uncomment below to test the serial
//#define TEST_SERIAL


// Uncomment below to test the spi code
//#define TEST_SPI

// Uncomment below to test the usb code
#define TEST_USB

【讨论】:

    【解决方案2】:
    #if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)
    

    【讨论】:

    • 是否需要添加括号或者可以是“#if !defined MANUF || ...”?
    • @TimK 从上面写的内容来看,我会说“是”。我很可能是错的;这只是一个假设。
    • 实际上你没有,但我推荐它以提高可读性。 godbolt.org/g/O48eun
    • 真的吗?这对我来说似乎更容易阅读,但这可能只是个人喜好:#if !defined MANUF || !defined SERIAL || !defined MODEL
    • 括号的一个好处是,如果 MANUF 恰好是一个复合语句(即 1 + 1),那么您将检查整个语句,而不仅仅是它的第一部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 2011-08-16
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    相关资源
    最近更新 更多