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

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

本文介绍了是否可以使用C预处理器来判断文件是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的代码库(读取:成千上万的模块),它有许多项目共享的代码,所有项目都使用不同的C ++编译器在不同的操作系统上运行。不用说,维护构建过程可能相当繁琐。

I have a very large codebase (read: thousands of modules) that has code shared across numerous projects that all run on different operating systems with different C++ compilers. Needless to say, maintaining the build process can be quite a chore.

在代码库中有几个地方可以清理代码,如果只有一种方法使预处理器忽略某些 #includes 如果文件不存在于当前文件夹中。有没有人知道一种方法来实现这一点?

There are several places in the codebase where it would clean up the code substantially if only there were a way to make the pre-processor ignore certain #includes if the file didn't exist in the current folder. Does anyone know a way to achieve that?

目前,我们使用 #ifdef c> #include 在第二个项目特定的文件#define是否在项目中存在 #include 。这工作,但它的丑陋。人们经常忘记在从项目中添加或删除文件时正确更新定义。我已经考虑编写一个预构建工具来保持这个文件是最新的,但如果有一个平台无关的方式来做这个预处理程序,我宁愿这样做。任何想法?

Presently, we use an #ifdef around the #include in the shared file, with a second project-specific file that #defines whether or not the #include exists in the project. This works, but it's ugly. People often forget to properly update the definitions when they add or remove files from the project. I've contemplated writing a pre-build tool to keep this file up to date, but if there's a platform-independent way to do this with the preprocessor I'd much rather do it that way instead. Any ideas?

推荐答案

通常这是通过使用脚本来尝试运行预处理器试图包括文件。根据预处理器是否返回错误,脚本将使用适当的#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

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

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

这篇关于是否可以使用C预处理器来判断文件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:00