3

I have written some code that make use c++17's charconv, that I can compile just fine with g++ 9. Even though I have set the std to c++17 in my CMakeLists.txt, cmake insists on using c++ 7.5, which does not support charconv.

How do I tell cmake that I need a compiler that supports charconv ? I see no switch in CMAKE_CXX_KNOWN_FEATURES.

Here is my CMakeLists.txt

cmake_minimum_required(VERSION 3.17)

file(GLOB CLIENT_SRC "srcs/*.cpp")
include_directories("includes")

add_executable(client ${CLIENT_SRC})

set_target_properties(client PROPERTIES OUTPUT_NAME "distff-client")

target_compile_features(client PUBLIC cxx_std_17 )
Barry
  • 286,269
  • 29
  • 621
  • 977
DontBreakAlex
  • 172
  • 1
  • 9
  • if on linux did you try to use update alternatives: https://stackoverflow.com/questions/7031126/switching-between-gcc-and-clang-llvm-using-cmake/12843988#12843988 – NoSenseEtAl May 01 '20 at 22:20

2 Answers2

3

Not a cmake guy... and I don't really understand cmake's approach to compile features here. But in C++ in general, we now use feature-test macros to detect the presence of features. You're looking specifically for __cpp_lib_to_chars.

I think you want to require compilation of this program:

#if __has_include(<version>)
#  include <version>
#elif __has_include(<charconv>)
#  include <charconv>
#else
#  error "neither <version> nor <charconv> available to test"
#endif

#ifndef __cpp_lib_to_chars
#  error "tochars not implemented"
#endif

Which can probably be generalized to something you can configure_file() for an arbitrary library feature (just pull out the header name and the macro name, and probably also check for the macro having the minimum required value).

Either way, if you try_compile() the resultant source file, you could probably get the behavior you want?

Barry
  • 286,269
  • 29
  • 621
  • 977
  • Thank you, I was not aware of try_compile(). How would you use it to pick a compiler ? I believe there's no way to get a list of installed compilers. The best I can do is ask the user the specify a different compiler. – DontBreakAlex Apr 26 '20 at 20:35
  • @DontBreakAlex Pick a compiler? I thought you pick the compiler. – Barry Apr 26 '20 at 20:46
  • Maybe I misunderstood, but I believe to point of target_compile_features() is to allow cmake to pick a compiler that supports them. If think I have to use autoconf if this is not the case, I have not idea what I'm doing. – DontBreakAlex Apr 26 '20 at 21:20
  • I think that CMake is not really extending `target_compile_features` (no C++17). You can see them defined here (for C++): https://cmake.org/cmake/help/latest/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.html – Stro Aug 05 '23 at 10:11
-1

Not a CMAKE expert, but the easiest would be to set the CXX environment variable. Like so:

export CXX="/usr/bin/x86_64-linux-gnu-g++-9"

see more at How to specify a compiler in CMake?

BeErikk
  • 74
  • 1
  • 7