Can the C preprocessor be used to tell if a file exists?(可以使用 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.
如果文件在当前文件夹.有谁知道实现这一目标的方法吗?
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?
目前,我们在共享文件中的 #include
周围使用 #ifdef
,并使用第二个项目特定文件 #defines#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
autoconf 是一个非常全面的框架,用于可移植地处理此类(以及数千个其他)可移植性检查.
这篇关于可以使用 C 预处理器来判断文件是否存在吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可以使用 C 预处理器来判断文件是否存在吗?
基础教程推荐
- C/C++编程中const的使用详解 2023-03-26
- 如何C++使用模板特化功能 2023-03-05
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- C利用语言实现数据结构之队列 2022-11-22
- 详解c# Emit技术 2023-03-25
- C语言基础全局变量与局部变量教程详解 2022-12-31
- C++中的atoi 函数简介 2023-01-05
- C++详细实现完整图书管理功能 2023-04-04
- 一文带你了解C++中的字符替换方法 2023-07-20
- C语言 structural body结构体详解用法 2022-12-06