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

查看:183
本文介绍了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 标志,好像有一个 #includefoo.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.

a href =http://stackoverflow.com/a/9945579/2038264>这个答案涵盖了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 example 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天全站免登陆