且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以使用C预处理器来判断文件是否存在?

更新时间:2023-01-29 19:51:35

通常这是通过使用脚本来尝试运行预处理器试图包括文件。根据预处理器是否返回错误,脚本将使用适当的#define(或#undef)更新生成的.h文件。在bash中,脚本可能像下面这样模糊:

Generally this is done by using a script that tries running the preprocessor on an attempt at including the file. Depending on if the preprocessor returns an error, the script updates a generated .h file with an appropriate #define (or #undef). In bash, the script might look vaguely like this:

cat > .test.h <<'EOM'
#include <asdf.h>
EOM
if gcc -E .test.h
 then
  echo '#define HAVE_ASDF_H 1' >> config.h
 else 
  echo '#ifdef HAVE_ASDF_H' >> config.h
  echo '# undef HAVE_ASDF_H' >> config.h
  echo '#endif' >> config.h
 fi

一个非常全面的框架,可移植地使用可移植性检查以及其他数千人)是 autoconf

A pretty thorough framework for portably working with portability checks like this (as well as thousands others) is autoconf.