如何包含可能存在或不存在的头文件? [英] How do you include a header file that may or may not exist?
问题描述
假设我在foo.h中定义了BAR.但是foo.h可能不存在.在没有编译器抱怨的情况下,如何包含它?
Let's assume I define BAR in foo.h. But foo.h might not exist. How do I include it, without the compiler complaining at me?
#include "foo.h"
#ifndef BAR
#define BAR 1
#endif
int main()
{
return BAR;
}
因此,如果在foo.h中将BAR定义为2,那么如果foo.h存在,则程序将返回2,如果foo.h不存在,则程序将返回1.
Therefore, if BAR was defined as 2 in foo.h, then the program would return 2 if foo.h exists and 1 if foo.h does not exist.
推荐答案
通常,您需要执行一些外部操作才能完成此操作-例如通过执行类似搜索路径的操作(如注释中所建议),并提供空的 foo.h
作为后备广告,或将 #include
包裹在 #ifdef HAS_FOO_H
... #endif
并通过编译器开关设置 HAS_FOO_H
(用于gcc/clang等的 -DHAS_FOO_H
).
In general, you'll need to do something external to do this - e.g. by doing something like playing around with the search path (as suggested in the comments) and providing an empty foo.h
as a fallback, or wrapping the #include
inside a #ifdef HAS_FOO_H
...#endif
and setting HAS_FOO_H
by a compiler switch (-DHAS_FOO_H
for gcc/clang etc.).
如果您知道使用的是特定的编译器,而可移植性不是问题,请注意,某些编译器确实支持以扩展名的形式包括可能存在或不存在的文件.例如,请参见clang的 __ has_include
功能.
If you know that you are using a particular compiler, and portability is not an issue, note that some compilers do support including a file which may or may not exist, as an extension. For example, see clang's __has_include
feature.
这篇关于如何包含可能存在或不存在的头文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!