C语言 预处理器检查是否未定义多个定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17237545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:44:48  来源:igfitidea点击:

Preprocessor check if multiple defines are not defined

cc-preprocessor

提问by Toby

I have a selection of #defines in a header that are user editable and so I subsequently wish to check that the defines exist in case a user deletes them altogether, e.g.

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

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

This works perfectly OK, I am wondering however if there is a better way to check if multiple defines are NOT in place... i.e. something like:

这完全可以,但我想知道是否有更好的方法来检查多个定义是否到位......即类似:

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

or maybe

或者可能

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

to remove the need for the empty #if section.

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

回答by Sergey L.

#if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)

回答by netskink

FWIW, @SergeyL's answer is great, but here is a slight variant for testing. Note the change in logical or to logical and.

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

main.c has a main wrapper like this:

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 and usb.c have main wrappers for their respective test code like this:

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 Which is included by all the c files has an entry like this:

包含在所有 c 文件中的 config.h 有一个这样的条目:

// 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