Check Which Compiler is Used in CMake

Check Which Compiler is Used in CMake

When developing cross-platform CMake-based projects, it's often useful to know which compiler is driving the build. Different compilers (like GCC, Clang, MSVC, or Intel) may require unique options, optimizations, or workarounds. Fortunately, CMake automatically detects the active compiler and exposes this information through built-in variables. This tutorial demonstrates how to check which compiler is used in CMake.

When a language such as C++ is enabled, CMake sets a variable named CMAKE_CXX_COMPILER_ID to identify the compiler in use. You can use this variable to conditionally configure the project. Here is simple CMakeLists.txt how to use this variable:

cmake_minimum_required(VERSION 3.27)
project(myapp)

set(CMAKE_CXX_STANDARD 17)

if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
    message(STATUS "GCC")
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
    message(STATUS "Clang")
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
    message(STATUS "MSVC")
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM")
    message(STATUS "Intel")
endif ()

add_executable(${PROJECT_NAME} main.cpp)

CMake automatically defines the variable CMAKE_<LANG>_COMPILER_ID when a language is enabled. Possible values include GNU, Clang, MSVC, IntelLLVM, and others depending on the toolchain. You can find the full list of recognized compiler IDs in the official CMake documentation.

If the project is written in C instead of C++, replace CXX with C (CMAKE_C_COMPILER_ID). This same pattern applies to other supported languages as well.

CMake provides a convenient shorthand variable called MSVC that is automatically defined when building with Microsoft MSVC compiler. This is often used to apply MSVC specific compiler options or suppress certain warnings.

# ...

if (MSVC)
    # ...
endif ()

# ...

Leave a Comment

Cancel reply

Your email address will not be published.