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.

<!–more–

Former way

Here follows the code used in dtk:

cmake 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:

cmake 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.

Depuis CMake 3.2, il est possible de forcer l’usage du standard c++11 (cf. Craig Scott’s blog post pour plus de détails). Jusqu’à présent, dans dtk, nous étions obligés de tester l’architecture (Apple, Unix or Windows), puis de vérifier si le compilateur supportait le c++11 et enfin nous devions fixer les flags correspondants manuellement. [/md]

Ancienne méthode

Voici l’extrait de code cmake utilisé jusqu’ici dans dtk:

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

On s’aperçoit aisément combien ce code est pénible et peu lisible.

Nouvelle approche

Désormais, il suffit de fixer deux variables CMake pour forcer l’usage du c++11:

cmake set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON)

Bien plus simple n’est-ce pas?

CMake fournit d’autres commandes pour utiliser plus finement les différentes fonctionalités du compilateur. Craig Scott les détaille très clairement dans son blog post.