Supreme Machine
Supreme Machine

Reputation: 69

C++ Cmake: How to test if compiler exists and select it

How in Cmake test if compiler exists and if true then select it? Or some function to manually set desired compiler and it`s toolchain inside CMakeLists.txt, without external env variables nor additional toolchain files / cmake args? Some proper way?

Something like:

if(find_compiler("clang"))
set(CMAKE_C_COMPILER "clang")
set(CMAKE_CXX_COMPILER "clang++")

But will it automatically set properly other toolchain variables and etc? Also I had found deprecated Cmake module CMakeForceCompiler that looks like exactly what I want, but it is deprecated as I said and in my version of CMake this module doesn't exists.

Upvotes: 1

Views: 142

Answers (2)

Shelton Liu
Shelton Liu

Reputation: 601

How in Cmake test if compiler exists and if true then select it? Or some function to manually set desired compiler and it`s toolchain inside CMakeLists.txt, without external env variables nor additional toolchain files / cmake args? Some proper way? But will it automatically set properly other toolchain variables and etc?

What you can control the compiler selection using a combination of logic checks in CMakeLists.txt:

cmake_minimum_required(VERSION 3.10)
project(test)

find_program(CLANG_COMPILER clang)
find_program(CLANGXX_COMPILER clang++)

if(CLANG_COMPILER AND CLANGXX_COMPILER)
    set(CMAKE_C_COMPILER "${CLANG_COMPILER}")
    set(CMAKE_CXX_COMPILER "${CLANGXX_COMPILER}")
else()
    message(STATUS "Clang compiler not found. Using the default compiler.")
endif()

...

You can practice with command-line arguments to specify the compiler when calling CMake commands: (automatically set properly)

> cmake -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ ..

Upvotes: 0

serkan
serkan

Reputation: 146

if you want to set it manually:

When it detects C and C++ compilers, it looks for the CC and CXX variables. Set the path of clang to the CC and CXX environment variables

export CC=/usr/bin/clang
export CXX=/usr/bin/clang++
cmake ..
  • To check inside cmake file
cmake_minimum_required(VERSION 3.1)
project(test)

find_program(CLANG_CXX_PATH clang++)

if (CLANG_CXX_PATH)
    set(CMAKE_CXX_COMPILER "clang++" CACHE INTERNAL "")
    message("Clang Found")
else()
    message("Clang not Found.")
endif()

Upvotes: 0

Related Questions