vlambda博客
学习文章列表

cmake跨平台对编译器的准确识别

cmake跨平台对编译器的准确识别:

使用 CMAKE_CXX_COMPILER_ID STREQUAL CompilerID 来判断.
CompilerID 包括 AppleClang(apple clang编译器), Clang(llvm的clang编译器),MSVC,GNU(gnu gcc编译器),Intel(intel icc编译器)等. 但是存在几个问题:

  1. Clang 和 AppleClang 都是clang编译器,如果不需要准确识别,可以用cmake的模式匹配判断,也就是 CMAKE_CXX_COMPILER_ID MATCHES "Clang"

  2. 对于visual studio上的clang-cl编译器,它的前端是clang,但后端是cl(msvc编译器),编译选项是msvc编译选项的子集, clang-cl检测到的CompilerID只是前端的Clang,如果要配置它的编译选项,需要用: CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC" 才能实现完整的匹配.

  3. 综上,可以使用下面的条件判断实现正确的编译器配置:

if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC" OR CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC") # 同时检测cl.exe和clang-cl.exe
# cl.exe 和 clang-cl.exe 配置
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
# clang-cl.exe 特殊配置
endif()
elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang") # 同时包括Clang和AppleClang
# clang编译器公有配置
if (CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang")
# apple-clang 特殊配置
endif()
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
# gcc 编译器配置
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Intel")
# intel icc 编译器配置
endif()

reference:

  1. https://stackoverflow.com/questions/10046114/in-cmake-how-can-i-test-if-the-compiler-is-clang

  2. https://stackoverflow.com/questions/50857779/cmake-detects-clang-cl-as-clang

  3. 3.https://gitlab.kitware.com/cmake/cmake/commit/541f079bd7ba7f141218ed93177af4d848e516fa