CMake builds for modern C++14, C++17, C++20

Non-standard language options and incomplete feature support are normal for compilers across virtually all programming languages from BASIC to Fortran and here C++. Because modern C++ features typically require using specific compiler flags to enable support, this can be confusing for those new to modern C++ features. Setup of C++ compiler flags for modern C++ features is easily and automatically handled by CMake.

While CMake allows testing for “known” C++ compiler functionality support, this list is necessarily quite incomplete. To test that a particular modern C++ feature (whether part of C++14, C++17, or C++20 or not) is implemented by a compiler in CMake is accomplished as follows. This particular example is for C++17 filesystem, a very useful incorporation of Boost::filesystem that existed for several years.

Example CMakeLists.txt is below. Variable cxx17fs is used to confirm C++17 filesystem support by this particular compiler for our program filesep.cpp.

cmake_minimum_required(VERSION 3.0)
project(fs CXX)

set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(CMAKE_REQUIRED_FLAGS -std=c++17)
include(CheckCXXSymbolExists)
CHECK_CXX_SYMBOL_EXISTS(std::filesystem::path::preferred_separator cxx17fs)

if(cxx17fs)
  add_executable(filesep_cpp filesep.cpp)
  set_property(TARGET filesep_cpp PROPERTY CXX_STANDARD 17)
endif()

Compilers supporting C++17 filesystem

With the CMakeLists.txt above, there will be output including:

– Looking for std::filesystem::path::preferred_separator - found

  • g++ ≥ 8
  • clang++

Compilers not yet supporting C++17 filesystem

With the CMakeLists.txt above, there will be output including:

– Looking for std::filesystem::path::preferred_separator - not found

  • Intel icpc 2019
  • pgc++

Tags:

Categories:

Comments

Written by Michael Hirsch, Ph.D. //