Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In CMake, how can I test if the compiler is Clang?

Tags:

c++

c

cmake

clang

We have a set of cross-platform CMake build scripts, and we support building with Visual C++ and GCC.

We're trying out Clang, but I can't figure out how to test whether or not the compiler is Clang with our CMake script.

What should I test to see if the compiler is Clang or not? We're currently using MSVC and CMAKE_COMPILER_IS_GNU<LANG> to test for Visual C++ and GCC, respectively.

like image 632
leedm777 Avatar asked Apr 06 '12 16:04

leedm777


People also ask

How does CMake detect compiler?

Inspecting the Default Compiler. When CMake is invoked to read a configuration file, temporary files are generated, including a cache and a CMakeFiles directory containing information specific to the environment. CMake uses this information to select the most appropriate compiler for the project.

What compiler does Clang use?

Clang uses the LLVM compiler as its back end and it has been included in the release of the LLVM since the LLVM 2.6. Clang is also built to be a drop-in replacement for GCC command. In its design, the Clang compiler has been constructed to work very similarly to GCC to ensure that portability is maximized.

Which C++ compiler does CMake use?

Usually under Linux, one uses CMake to generate a GNU make file which then uses gcc or g++ to compile the source file and to create the executable. A CMake project is composed of source files and of one or several CMakeLists.


1 Answers

A reliable check is to use the CMAKE_<LANG>_COMPILER_ID variables. E.g., to check the C++ compiler:

if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")   # using Clang elseif (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")   # using GCC elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Intel")   # using Intel C++ elseif (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")   # using Visual Studio C++ endif() 

These also work correctly if a compiler wrapper like ccache is used.

As of CMake 3.0.0 the CMAKE_<LANG>_COMPILER_ID value for Apple-provided Clang is now AppleClang. To test for both the Apple-provided Clang and the regular Clang use the following if condition:

if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")   # using regular Clang or AppleClang endif() 

Also see the AppleClang policy description.

CMake 3.15 has added support for both the clang-cl and the regular clang front end. You can determine the front end variant by inspecting the variable CMAKE_CXX_COMPILER_FRONTEND_VARIANT:

if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")   if (CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC")     # using clang with clang-cl front end   elseif (CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU")     # using clang with regular front end   endif() endif() 
like image 92
sakra Avatar answered Nov 10 '22 01:11

sakra