当我试图运行一个CMake生成的makefile来编译我的程序时,我得到的错误是

c++ 98模式不支持基于范围的for循环。

我尝试添加add_definitions(-std=c++0x)到我的CMakeLists.txt,但它没有帮助。

我也试过这个:

if(CMAKE_COMPILER_IS_GNUCXX)
    add_definitions(-std=gnu++0x)
endif()

当我执行g++——version时,我得到:

g+ (Ubuntu/Linaro 4.6.1- 9u阑尾3)4.6.1

我还尝试了SET(CMAKE_CXX_FLAGS "-std=c++0x"),这也不起作用。

我不明白如何使用CMake激活c++ 11特性。


当前回答

现代的方法是通过以下方式指定c++ 11所需的最低标准:

target_compile_features(foo PUBLIC cxx_std_11)

这种方式:

CMake can honor default C++ standard of the compiler if it's greater than C++11 You can clearly specify whether C++ standard is required at build time, consume time, or both. This is nice for libraries. Public compile features are propagated to downstream targets, so it comes for free in those targets even if they don't directly use this feature. Users can externally set another C++ standard (more recent basically), with CMAKE_CXX_STANDARD, either from command line or CMake presets. If you hardcode CMAKE_CXX_STANDARD in a CMakeLists, nobody can override the C++ standard without editing your CMakeLists, which is not very pleasant.

它需要CMake >= 3.8

其他回答

对我来说有用的是在你的CMakeLists.txt中设置以下行:

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

设置此命令将激活编译器的c++ 11特性,并且在执行cmake ..命令,您应该能够在代码中使用基于范围的for循环,并编译它而不会出现任何错误。

最简单的方法:

add_compile_options(化= c + + 11)

事实证明,SET(CMAKE_CXX_FLAGS "-std=c++0x")确实激活了许多c++ 11特性。它不起作用的原因是这个语句看起来是这样的:

set(CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS} -g -ftest-coverage -fprofile-arcs")

按照这种方法,-std=c++0x标志不知何故被覆盖,它不起作用。逐一设置标志或使用列表方法是有效的。

list( APPEND CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS} -g -ftest-coverage -fprofile-arcs")

这是启用c++ 11支持的另一种方式,

ADD_DEFINITIONS(
    -std=c++11 # Or -std=c++0x
    # Other flags
)

我遇到过只有这个方法有效而其他方法失败的例子。也许和最新版本的CMake有关。

CMake命令target_compile_features()用于指定所需的c++特性cxx_range_for。然后,CMake将引入要使用的c++标准。

cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)
project(foobar CXX)
add_executable(foobar main.cc)
target_compile_features(foobar PRIVATE cxx_range_for)

不需要使用add_definitions(-std=c++11)或修改CMake变量CMAKE_CXX_FLAGS,因为CMake将确保使用适当的命令行标志调用c++编译器。

也许你的c++程序使用了其他c++特性而不是cxx_range_for。CMake全局属性CMAKE_CXX_KNOWN_FEATURES列出了你可以选择的c++特性。

除了使用target_compile_features(),你还可以通过设置CMake属性显式地指定c++标准 CXX_STANDARD 而且 你的CMake目标的CXX_STANDARD_REQUIRED。

请参见我更详细的回答。