Search code examples
c++cmakebuildcompilationbuild-system

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.


Solution

  • 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()