cmake include header into every source file(cmake 将头文件包含到每个源文件中)
问题描述
我其实有一个简单的问题,但找不到答案.也许你可以指出我的重复.所以,问题是:是否可以告诉 cmake 指示编译器在每个源文件的开头自动包含一些头文件,这样就不需要放置 #include foo.h?谢谢!
I actually have a simple question, but couldn't find an answer. Maybe you can point me to a duplicate. So, the question is: is it possible to tell cmake to instruct a compiler to automatically include some header at the beginning of every source file, so there would be no need to put #include foo.h? Thanks!
推荐答案
CMake 没有针对此特定用例的功能,但正如您所暗示的,GCC 等编译器具有 -include
标志,就像源文件中存在 #include "foo.h"
一样,并且由于 CMake 可以将参数传递给编译器,因此您可以通过 add_definitions
来实现>.
CMake doesn't have a feature for this specific use case, but as you've hinted, compilers such as GCC have the -include
flag which acts as if there was an #include "foo.h"
in the source file, and since CMake can pass arguments to compilers, you can do it via add_definitions
.
这个答案涵盖了 GCC、Clang 和 MSVC 的标志,它们应该涵盖很多基础.所以在 CMake 中,检测编译器是什么并传递适当的标志.
This answer covers what the flag is for GCC, Clang and MSVC which should cover a lot of bases. So in CMake, detect what the compiler is and pass the appropriate flag.
CMake 代码可能如下所示:
Here's what the CMake code might look like:
if(MSVC)
add_definitions(/FI"foo.h")
else()
# GCC or Clang
add_definitions(-include foo.h)
endif()
评论
总的来说,这样做是个坏主意.代码检查工具(如 IDE 或 doxygen)会被它弄糊涂,更不用说其他人在查看代码了.如果不是所有的源文件实际上都需要定义,添加额外的 #include
会减慢编译时间.如果您确实需要在所有源文件中使用相同的标头(并且它不是系统标头),则这可能是代码中高耦合的征兆.又有什么好处呢?不必在文件中添加一行?
Comments
In general, doing this is a bad idea. Code inspection tools (like IDEs, or doxygen) will be confused by it, not to mention other humans looking at the code. If not all source files actually require the definition, adding extra #include
s will slow down compile time. If you actually do need the same header (and it's not a system header) in all your source files, it may be symptomatic of high coupling in your code. And for what benefit? Not having to add one line to your files?
然而,有必要注意编译器支持这一点是有原因的;有一些奇怪的边缘情况(示例 1、示例 2),这是一件很有用的事情.
However, it's necessary to note that compilers support this for a reason; there are a few weird edge cases (example 1, example 2) where it's a useful thing to do.
请注意,您这样做是出于正确的原因.
Just be aware that you're doing this for the right reasons.
这篇关于cmake 将头文件包含到每个源文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:cmake 将头文件包含到每个源文件中
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01