当我试图运行一个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特性。


当前回答

OS X和Homebrew LLVM相关:

不要忘记在它之后调用cmake_minimum_required(VERSION 3.3)和project() !

或者CMake将隐式地在第1行之前插入project(),导致Clang版本检测出现问题,并可能出现其他类型的问题。这是一个相关的问题。

其他回答

现代的方法是通过以下方式指定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

现代cmake提供了更简单的方法来配置编译器以使用特定版本的c++。所有人需要做的唯一一件事就是设置相关的目标属性。在cmake支持的属性中,用于确定如何配置编译器以支持特定版本的c++的属性如下:

CXX_STANDARD设置c++标准,它的特性被请求来构建目标。将此值设置为11,以目标c++ 11。 CXX_EXTENSIONS,一个布尔值,指定是否请求特定于编译器的扩展。将此设置为Off将禁用对任何特定于编译器的扩展的支持。

为了演示,这里有一个CMakeLists.txt的最小工作示例。

cmake_minimum_required(VERSION 3.1)

project(testproject LANGUAGES CXX )

set(testproject_SOURCES
    main.c++
    )

add_executable(testproject ${testproject_SOURCES})

set_target_properties(testproject
    PROPERTIES
    CXX_STANDARD 11
    CXX_EXTENSIONS off
    )

如果你想总是激活最新的c++标准,这里是我对David Grayson的答案的扩展,根据最近(CMake 3.8和CMake 3.11)为CMAKE_CXX_STANDARD增加了17和20的值:

IF (CMAKE_VERSION VERSION_LESS "3.8")
    SET(CMAKE_CXX_STANDARD 14)
ELSEIF (CMAKE_VERSION VERSION_LESS "3.11")
    SET(CMAKE_CXX_STANDARD 17)
ELSE()
    SET(CMAKE_CXX_STANDARD 20)
ENDIF()

# Typically, you'll also want to turn off compiler-specific extensions:
SET(CMAKE_CXX_EXTENSIONS OFF)

(在链接答案中的set (CMAKE_CXX_STANDARD 11)中使用该代码。)

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

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

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

我在用

include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
        message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()

但是如果你想要使用c++ 11, g++ 4.6.1已经相当老了。 尝试使用更新的g++版本。