C 代码的可靠可移植性,无需依赖预处理器
依靠预处理器和预定义的编译器宏来实现可移植性似乎很难管理。实现 C 项目可移植性的更好方法是什么?我想将特定于环境的代码放入行为相同的标头中。有没有办法让构建环境选择要包含哪些标头?
我想我应该将特定于环境的标头放入特定环境的目录中。然后,构建环境只需将标头从平台目录复制到根目录,构建项目,然后删除副本。
Relying on the preprocessor and predefined compiler macros for achieving portability seems hard to manage. What's a better way to achieve portability for a C project? I want to put environment-specific code in headers that behave the same way. Is there a way to have the build environment choose which headers to include?
I was thinking that I'd put the environment-specific headers into directories for specific environments. The build environment would then just copy the headers from the platform's directory into the root directory, build the project, and then remove the copies.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然,这完全取决于您的构建环境,与 C 本身无关。
您可以尝试的一件事是在 makefile 中设置包含路径:
并取消注释您正在处理的路径。然后将平台特定的标头放入这些目录中:
在紧要关头,您甚至可以拥有不同的平台 makefile,例如
solaris.mk
和windows.mk
,而不必进行编辑任何文件。但我不认为你对预处理器有什么反感,这是它擅长的事情之一,而且几十年来人们一直在成功地做到这一点。最重要的是,当您的代码需要根据平台进行更改时会发生什么。您可以将代码抽象到头文件中,但这对我来说似乎比几个
#ifdef
更难管理。That depends entirely on your build environment of course and has nothing to do with C itself.
One thing you can try is to set up your include paths in your makefiles thus:
and uncomment the one you're working on. Then put your platform specific headers in those directories:
You could, at a pinch, even have different platform makefiles such as
solaris.mk
andwindows.mk
and not have to edit any files at all.But I don't see your aversion to the preprocessor, that's one of the things it's good at, and people have been doing it successfully for decades. On top of that, what happens when your code needs to change per-platform. You can abstract the code into header files but that seems far harder to manage than a few
#ifdef
s to me.这基本上就是配置脚本的作用 - 即确定系统的细节,然后修改该系统的 makefile。看看 GNU autoconf 的文档,它可能会做什么你想要的,尽管我不确定如果有必要的话它对 Windows 的便携性如何。
This is basically what a configure script does - i.e. work out the specifics of the system and then modify the makefile for that system. Have a look at the documentation for GNU autoconf, it might do what you want, although I'm not sure how portable it would be to windows if that is necessary.
pax的答案很好,但我要补充一点,您可以
MyFileOpen()
,它在unix上调用fopen
,在windows上调用其他东西。现在,代码中唯一存在与文件打开相关的预处理器问题的部分是 MyFileOps 模块。pax's answer is good, but I'll add that you can
MyFileOpen()
which callsfopen
on unix and something else on windows. Now the only part of your code that has any preprocessor cruft related to file opening is the MyFileOps module.