是否有一个优雅的解决方案来检查是否定义了预处理器符号

Is there an elegant solution for checking whether a preprocessor symbol is defined or not

由于预处理器在检查实际未定义的预处理器符号的值时不会报告错误(通常是由于缺少#include "some_header.h"),所以我将这种繁琐的三行结构与 "defined":

#if !defined(SOME_SYMBOL)
#error "some symbol isn't defined"
#endif
#if SOME_SYMBOL == 1
// Here is my conditionally compiled code
#endif

和“#ifndef”的方法一样。
有没有更优雅的方法来执行此检查?

在您的构造中,您可以使用 else 块来跳过对定义的检查:

#if SOME_SYMBOL == 1
// Here is my conditionally compiled code
#else
// error
#endif

但原则上评论是正确的。 #if !defined 和 shorthand #ifndef 是两个可用版本。

目前,您正在检查 SOME_SYMBOL 是否等于 1。您是否根据该值执行不同的代码? 如果没有,您可以简单地使用:

#ifdef SOME_SYMBOL
// Here is my conditionally compiled code
#else
// error
#endif

现在距离典型的 c++ include guards 仅一步之遥。从维基百科 link 复制,这是一个 grandparent.h 文件:

#ifndef GRANDPARENT_H
#define GRANDPARENT_H

struct foo {
    int member;
};

#endif /* GRANDPARENT_H */

现在,即使您最终包含此 header 两次,它也只会执行一次。