Enabling C++11 (C++0x) in CMake

Going over some CMakeLists.txt files I’ve written, I came across the following snippet:

include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
        message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()

Various versions of gcc and clang use different flags to specify C++11 support; namely, older ones accept -std=c++0x and newer ones accept -std=c++11. The above snippet detects which one is the right one for the compiler being used and adds the flag to CXX_FLAGS.

6 thoughts on “Enabling C++11 (C++0x) in CMake”

Leave a Reply

Your email address will not be published. Required fields are marked *