Goals
Make cmake
select clang++
if its version is above 10
; otherwise, use g++
. If clang++
is below 10
and the default g++
is below 10.1
, use g++-10
(REQUIRED
).
This is to achieve compiler fallback.
Background
As kindly noted in this answer, one should set the default compiler before the project
keyword.
Instead of using
-DCMAKE_CXX_COMPILER=clang++
or
set(CMAKE_CXX_COMPILER clang++)
I used the following statements with reference to the answer here:
find_program(CMAKE_CXX_COMPILER
NAMES $ENV{CXX} clang++ PATHS ENV PATH NO_DEFAULT_PATH)
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 10)
find_program(CMAKE_CXX_COMPILER
NAMES $ENV{CXX} g++ PATHS ENV PATH NO_DEFAULT_PATH)
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 10.1)
find_program(CMAKE_CXX_COMPILER
NAMES $ENV{g++-10} g++-10 PATHS ENV PATH NO_DEFAULT_PATH REQUIRED)
endif()
endif()
Problem
The compiler is not set to g++
when the version of clang++
is less than 10
, but I could check that cmake
passes the branch
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 10)
I do not understand this behavior. And are there any alternative to this without using command line arguments?
UPDATE
This question was asked in acknowledgment of the fact that setting a compiler in CMakeLists.txt
is discouraged.
@KamilCuk suggested two ways to achieve what I stated, and one may take those suggestions if they want to.
Here's what I did.
TL;DR
Do not specify a compiler in CMakeLists.txt
.
My suggestion
This is contrary to what I have previously done in this question.
I scrapped all the configuration logic from CMakeLists.txt
and decided to create a shell file that extracts compiler versions and select an appropriate compiler. This way of configuration is quite well-known, which can be found in many popular repositories such as ImageMagick and tensorflow.