Friday, October 29, 2021

[SOLVED] How `CMAKE_C_COMPILER_ID MATCHES "Clang|GNU"` works?

Issue

I want to build my project using Clang as first choice, if Clang doesn't exist, and compile it by GCC, but in my practice, Cmake always choose GCC.

cmake_minimum_required (VERSION 2.8.12)
project (leptjson_test C)

if (CMAKE_C_COMPILER_ID MATCHES "Clang|GNU")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -pedantic -fsanitize=address -fsanitize=undefined -Wall")
endif()

add_library(leptjson leptjson.c)
add_executable(leptjson_test test.c)
target_link_libraries(leptjson_test leptjson)

Solution

How CMAKE_C_COMPILER_ID MATCHES "Clang|GNU" works?

It matches the string stored in CMAKE_C_COMPILER_ID against extended regex expression Clang|GNU.

I want to build my project using Clang as first choice, if Clang doesn't exist, and compile it by GCC

Looking at CMakeDetermineCCompiler.cmake set CMAKE_C_COMPILER_LIST to the list of your compilers. You could do:

cmake_minimum_required(...)
if(LEPTJSON_DEV)  # my recommendation
    set(CMAKE_C_COMPILER_LIST clang gcc)
endif()
project(...)

I recommend to set your custom settings protected with some variable, so that other people can use your library too without your settings.



Answered By - KamilCuk