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.
CMake 3.1 introduced the CMAKE_CXX_STANDARD variable that you can use. If you know that you will always have CMake 3.1 available, you can just write this in your top-level CMakeLists.txt file, or put it right before any new target is defined:
If you need to support older versions of CMake, here is a macro I came up with that you can use:
The macro only supports GCC right now, but it should be straight-forward to expand it to other compilers.
Then you could write
use_cxx11()
at the top of any CMakeLists.txt file that defines a target that uses C++11.CMake issue #15943 for clang users targeting macOS
If you are using CMake and clang to target MacOS there is a bug that can cause the
CMAKE_CXX_STANDARD
feature to simply not work (not add any compiler flags). Make sure that you do one of the following things:Set policy CMP0025 to NEW with the following code at the top of your CMakeLists.txt file before the
project
command:For CMake 3.8 and newer you can use
The easiest way:
add_compile_options(-std=c++11)
The CMake command
target_compile_features()
is used to specify the required C++ featurecxx_range_for
. CMake will then induce the C++ standard to be used.There is no need to use
add_definitions(-std=c++11)
or to modify the CMake variableCMAKE_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 propertyCMAKE_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 propertiesCXX_STANDARD
andCXX_STANDARD_REQUIRED
for your CMake target.See also my more detailed answer.
I am using
But if you want to play with
C++11
,g++ 4.6.1
is pretty old. Try to get a newerg++
version.What works for me is to set the following line in your CMakeLists.txt:
Setting this command activates the C++11 features for the compiler and after executing the
cmake ..
command, you should be able to userange based for loops
in your code and compile it without any errors.