CMake 3.1 introduced the CMAKE_CXX_STANDARD variable that you can use. If you know that you will always have CMake 3.1 or later available, you can just write this in your top-level CMakeLists.txt file, or put it right before any new target is defined:
set (CMAKE_CXX_STANDARD 11)
If you need to support older versions of CMake, here is a macro I came up with that you can use:
macro(use_cxx11)
if (CMAKE_VERSION VERSION_LESS "3.1")
if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")
endif ()
else ()
set (CMAKE_CXX_STANDARD 11)
endif ()
endmacro(use_cxx11)
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:
Use cmake_minimum_required to require CMake 3.0 or later, or
Set policy CMP0025 to NEW with the following code at the top of your CMakeLists.txt file before the project
command:
if (POLICY CMP0025)
cmake_policy(SET CMP0025 NEW)
endif ()
SET(CMAKE_CXX_FLAGS "-std=c++0x")
works fine for me, so there is probably a problem somewhere else in the CMakeLists file. Make sure you don't accidentally overwrite the contents of CMAKE_CXX_FLAGS later on. – ComicSansMSset(CMAKE_CXX_STANDARD 11)
(before defining the target) is the best way. – emlaiCXX_STANDARD
does not work on MSVC, so basically you have to fall back totarget_compile_features
if you want something that works cross-platform. – Ela782