cmake 将头文件包含到每个源文件中 [英] cmake include header into every source file

查看:27
本文介绍了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 #includes 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 将头文件包含到每个源文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆