Enforce c++11 flags using cmake

Since CMake 3.2, it is possible to enforce in very simple way the use of c++11 features (see Craig Scott’s blog post for more details). Until now in dtk, we had to test the architecture (Apple, Unix or Windows), then check whether the compiler provides c++11 support or not and eventually set dedicated flags manually.

Former way

Here follows the code used in dtk:

if(APPLE)
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -I/usr/lib/c++/v1")
endif(APPLE)

if(NOT APPLE AND NOT MSVC)

  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()

else(NOT APPLE AND NOT MSVC)

  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")

endif(NOT APPLE AND NOT MSVC)

One can see how painful and not really readable it was.

New method

We now just have to add two variable definitions to enforce the use of c++11 features:

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

Obviously, this way is easier.

CMake provides finer tuning as far as the compiler features are concerned. Craig Scott details them very clearly in his post.

About Thibaud Kloczko

Graduated in CFD, Thibaud Kloczko is a software engineer at Inria. He is involved in the development of the meta platform dtk that aims at speeding up life cycle of business codes into research teams and at sharing software components between teams from different scientific fields (such as medical and biological imaging, numerical simulation, geometry, linear algebra, computational neurology).

Leave a Reply

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

Time limit is exhausted. Please reload the CAPTCHA.