如何让 CMake 基于 GCC 版本通过 std=c++14/c++1y 或 c++17/c++1z?

How to get CMake to pass either std=c++14/c++1y or c++17/c++1z based on GCC version?(如何让 CMake 基于 GCC 版本通过 std=c++14/c++1y 或 c++17/c++1z?)

本文介绍了如何让 CMake 基于 GCC 版本通过 std=c++14/c++1y 或 c++17/c++1z?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC 4.x 不接受 C++14 代码的 --std=c++14 开关 - 它需要 --std=c++1y 代替.更高版本采用 --std=c++1z 但(可能)不是 --std=c++17 尚未设置(在 2016 年编写).也许 C++11 也有类似的问题.

GCC 4.x doesn't accept the --std=c++14 switch for C++14 code - it takes --std=c++1y instead. Later versions take --std=c++1z but (probably) not --std=c++17 which has not been set yet (writing this in 2016). Perhaps there are similar issues with C++11.

CMake 是否有一些工具(也许作为一个模块)来根据 GCC 版本传递正确的开关?

Does CMake have some facility (perhaps as a module) to pass the correct switch according to the GCC version?

推荐答案

当想要指定特定的 C++ 版本时,推荐使用 CMake 3.1 及更高版本执行此操作的方法是使用 CXX_STANDARDCXX_STANDARD_REQUIREDCXX_EXTENSIONS 目标属性,或它们的变量等效项以指定目标默认值.可以在此处找到完整的详细信息,但简短的版本是像这样:

When wanting to specify a particular C++ version, the recommended way to do this with CMake 3.1 and later is to use the CXX_STANDARD, CXX_STANDARD_REQUIRED and CXX_EXTENSIONS target properties, or their variable equivalents to specify target defaults. Full details can be found here, but the short version goes something like this:

cmake_minimum_required(VERSION 3.1)
project(Example)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# ... Define targets, etc. as usual

然后,CMake 应根据编译器支持的内容为请求的 C++ 标准选择适当的编译器标志,如果不支持请求的标准,则出错.

CMake should then select the appropriate compiler flag for the requested C++ standard based on what the compiler supports, or error out if it doesn't support the requested standard.

还应注意,CMake 可能会升级目标以使用比其 CXX_STANDARD 目标属性指定的语言标准更高的语言标准.编译功能需求的使用(如@FlorianWolters 的回答中所述)可以提高语言标准要求.事实上,CMake 将始终选择由 CXX_STANDARD 目标属性或在目标上设置的编译功能要求指定的更强的语言要求.另请注意,3.10.1 的 CMake 文档并未准确反映 CXX_EXTENSIONS 与编译功能交互的方式,因为 CXX_EXTENSIONS 仅在 CXX_STANDARD 也为大多数常见的编译器指定(因为它们与一个编译器标志一起指定).

It should also be noted that CMake may upgrade the target to use a later language standard than the one specified by its CXX_STANDARD target property. The use of compile feature requirements (as mentioned in @FlorianWolters answer) can raise the language standard requirement. In fact, CMake will always pick the stronger language requirement specified by either the CXX_STANDARD target property or the compile feature requirements set on the target. Note also that the CMake documentation as of 3.10.1 does not accurately reflect the way CXX_EXTENSIONS interacts with compile features, as CXX_EXTENSIONS only takes effect if CXX_STANDARD is also specified for most common compilers (since they are specified together with the one compiler flag).

这篇关于如何让 CMake 基于 GCC 版本通过 std=c++14/c++1y 或 c++17/c++1z?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何让 CMake 基于 GCC 版本通过 std=c++14/c++1y 或 c++17/c++1z?

基础教程推荐