在CMake中设置通用编译标志的现代方法是什么

在CMake中设置通用编译标志的现代方法是什么

本文介绍了在CMake中设置通用编译标志的现代方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CMake提供了多种机制来获取标志给编译器:

There are multiple mechanisms offered by CMake for getting flags to the compiler:





  • CMAKE_<LANG>_FLAGS_<CONFIG> variables
  • add_compile_options command
  • set_target_properties command

优先于其他在现代使用?如果是这样为什么?

Is there one method that is preferred over the other in modern use? If so why? Also, how can this method be used with multiple configuration systems such as MSVC?

推荐答案

对于现代CMake(版本2.8.12和您应该使用,它在内部使用目标属性。

For modern CMake (versions 2.8.12 and up) you should use target_compile_options, which uses target properties internally.

CMAKE_< LANG> _FLAGS 是一个全局变量,容易出错。它也不支持,它可以非常方便。

CMAKE_<LANG>_FLAGS is a global variable and the most error-prone to use. It also does not support generator expressions, which can come in very handy.

add_compile_options 基于目录属性,在某些情况下可以正常使用,但通常不会

add_compile_options is based on directory properties, which is fine in some situations, but usually not the most natural way to specify options.

target_compile_options 在每个目标基础上工作(通过设置和目标属性),通常会导致最干净的CMake代码,因为源文件的编译选项由文件所属的项目(而不是硬盘上的哪个目录)决定。这具有额外的优点,它传递到依赖目标。

target_compile_options works on a per-target basis (through setting the COMPILE_OPTIONS and INTERFACE_COMPILE_OPTIONS target properties), which usually results in the cleanest CMake code, as the compile options for a source file are determined by which project the file belongs to (rather than which directory it is placed in on the hard disk). This has the additional advantage that it automatically takes care of passing options on to dependent targets if requested.

即使它们稍微冗长一些,每个目标命令允许一个合理的细粒度控制在不同的构建选项和(在我个人的经验)是最不可能导致头痛的长期。

Even though they are little bit more verbose, the per-target commands allow a reasonably fine-grained control over the different build options and (in my personal experience) are the least likely to cause headaches in the long run.

理论上,你也可以直接设置相应的属性使用 set_target_properties ,但 target_compile_options 通常更易读。

In theory, you could also set the respective properties directly using set_target_properties, but target_compile_options is usually more readable.

例如,要根据使用生成器表达式的配置设置目标的编译选项 foo

For example, to set the compile options of a target foo based on the configuration using generator expressions you could write:

target_compile_options(foo PUBLIC "$<$<CONFIG:DEBUG>:${MY_DEBUG_OPTIONS}>")
target_compile_options(foo PUBLIC "$<$<CONFIG:RELEASE>:${MY_RELEASE_OPTIONS}>")

这篇关于在CMake中设置通用编译标志的现代方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 10:31