[C++11] How to activate C++ 11 in CMake?


The CMake command target_compile_features() is used to specify the required C++ feature cxx_range_for. CMake will then induce the C++ standard to be used.

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)

There is no need to use add_definitions(-std=c++11) or to modify the CMake variable CMAKE_CXX_FLAGS, because CMake will make sure the C++ compiler is invoked with the appropriate command line flags.

Maybe your C++ program uses other C++ features than cxx_range_for. The CMake global property CMAKE_CXX_KNOWN_FEATURES lists the C++ features you can choose from.

Instead of using target_compile_features() you can also specify the C++ standard explicitly by setting the CMake properties CXX_STANDARD and CXX_STANDARD_REQUIRED for your CMake target.

See also my more detailed answer.


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:


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.

What works for me is to set the following line in your CMakeLists.txt:

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

Setting this command activates the C++11 features for the compiler and after executing the cmake .. command, you should be able to use range based for loops in your code and compile it without any errors.

OSX and homebrewed LLVM related:

Don't forget to call cmake_minimum_required(VERSION 3.3) and project() after it!

Or cmake will insert project() implicitly before line 1 causing trouble with clang version detection and possibly other sorts of troubles. Here is related issue

The easiest way to set cxx standard is

 set_property(TARGET tgt PROPERTY CXX_STANDARD 11)

See cmake doc for more details.

The easiest way: