How do you include a header file that may or may not exist?

偶尔善良 提交于 2021-01-20 04:21:48

问题


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;
}

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.


回答1:


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.).

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.




回答2:


Use a tool like GNU Autoconf, that's what it's designed for. (On windows, you may prefer to use CMake).

So in your configure.ac, you'd have a line like:

AC_CHECK_HEADERS([foo.h])

Which, after running configure, would define HAVE_FOO_H, which you can test like this:

#ifdef HAVE_FOO_H
#include "foo.h"
#else
#define BAR 1
#endif

If you intend to go down the autotools route (that is autoconf and automake, because they work well together), I suggest you start with this excellent tutorial.



来源:https://stackoverflow.com/questions/11569659/how-do-you-include-a-header-file-that-may-or-may-not-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!