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


当前回答

我想这两行就够了。

set(CMAKE_CXX_STANDARD 11)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=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

设置Cxx标准最简单的方法是:

 set_property(TARGET tgt PROPERTY CXX_STANDARD 11)

有关更多细节,请参阅CMake文档。

以防你在使用cmake时遇到和我一样的错误。 你需要设置

set (CMAKE_CXX_STANDARD 11)

激活线程,因为它只支持c++ 11++

希望这能有所帮助

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

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

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

对于CMake 3.8和更新版本,您可以使用

target_compile_features(target PUBLIC cxx_std_11)

如果您希望在工具链不能遵循此标准的情况下生成步骤失败,则可以将此设置为必需的。

set_target_properties(target PROPERTIES CXX_STANDARD_REQUIRED ON)

如果你想严格遵守标准c++,即避免你的编译器提供的c++扩展(如GCC的-std=gnu++17),另外设置

set_target_properties(target PROPERTIES CXX_EXTENSIONS OFF)

这是在现代CMake介绍->添加功能-> c++ 11和超越详细文档。它还提供了关于如何在旧版本的CMake上实现这一点的建议,如果你受到限制的话。