How to activate C++ 11 in CMake?

2019-01-01 02:44发布

When I try to run CMake generated makefile to compile my program, I get the error that

range based for loops are not supported in C++ 98 mode.

I tried adding add_definitions(-std=c++0x) to my CMakeLists.txt, but it did not help. I tried this too:

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

When I do g++ --version, I get:

g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1

I have also tried SET(CMAKE_CXX_FLAGS "-std=c++0x"), which also does not work.

I do not understand how I can activate C++ 11 features using CMake.

标签: c++11 cmake
13条回答
还给你的自由
2楼-- · 2019-01-01 03:36

On modern CMake (>= 3.1) best way to set global requirement is:

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

It translates to "I want C++11 for all targets, it's not optional, I dont't want to use any GNU or MS extensions." As of c++17, this still is IMHO the best way.

Source: https://crascit.com/2015/03/28/enabling-cxx11-in-cmake/

查看更多
登录 后发表回答