如何在 CMake 中启用 C++17
我使用的是 VS 15.3,它支持集成的 CMake 3.8.如何在不为每个特定编译器编写标志的情况下以 C++17 为目标?我当前的全局设置不起作用:
I'm using VS 15.3, which supports integrated CMake 3.8. How can I target C++17 without writing flags for each specific compilers? My current global settings don't work:
# https://cmake.org/cmake/help/latest/prop_tgt/CXX_STANDARD.html
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# expected behaviour
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++lastest")
我希望 CMake 在生成 VS 解决方案文件时添加/std:c++lastest"或等效项,但未找到 c++17 标志,导致编译器错误:
I expected CMake to add "/std:c++lastest" or equivalents when generating VS solution files, but no c++17 flags was found, resulted in compiler error:
C1189 #error: class template optional is only available with C++17.
推荐答案
您的方法是正确的,但它不适用于 3.10 之前的 CMake 版本的 MSVC.
Your approach is the correct one, but it will not work for MSVC on versions of CMake prior to 3.10.
来自 CMake 3.9 文档:
对于没有标准级别概念的编译器,例如 MSVC,这不起作用.
For compilers that have no notion of a standard level, such as MSVC, this has no effect.
简而言之,CMake 尚未更新以适应添加到 VC++ 2017 的标准标志.
In short, CMake haven't been updated to accommodate for the standard flags added to VC++ 2017.
您必须检测是否使用了 VC++ 2017(或更高版本)并暂时自行添加相应的标志.
You have to detect if VC++ 2017 (or later) is used and add the corresponding flags yourself for now.
在 CMake 3.10(及更高版本)中,此问题已针对较新版本的 VC++ 修复.请参阅3.10 文档.
In CMake 3.10 (and later) this have been fixed for newer version of VC++. See the 3.10 documentation.
相关文章