使用预处理指令检查是否包含 header?

Check if header is included using preprocessing directives?

是否可以使用预处理指令测试文件是否已被包含?

我想实现这样的目标:

#ifincluded assert.h
#error "Should not include assert.h"
#endif

目前,我知道 assert.h 已经定义了 _ASSERT_H 来解决这个问题。在这种情况下,我可以使用 #ifdef _ASSERT_H。问题是这是特定于实现的。

有没有更好的方法来实现这个?

你可以简单地利用 assert() 本身是一个宏这一事实,所以你可以只做一个

#ifdef assert
#error "Should not include assert.h"
#endif

当然,如果有人定义了他们自己的 assert 宏,这也会抱怨,严格来说,这是合法的事情 as long as they don't include any standard header

在一天结束时,我会重新考虑您认为您在这里尝试做的事情。如果您处于必须确保某人不包含特定标准 header 的地步,那么您很可能走错了路,并且很可能会找到更好但完全不同的方法,如果您只需退后一步,从头开始重新思考。所以

Is there a better way to achieve this?

几乎可以肯定。但它与根据是否包含标准库的特定部分来检测和调整行为没有任何关系……