CMake default generator introspection

CMake can tell the default generator for the current platform without configuring a project. This is useful for build scripts that want to detect the generator default for CMake without having to configure a project first.

On Unix-like platforms, the default generator is typically “Unix Makefiles”. On Windows, the default generator is the latest Visual Studio version installed on the system and supported by CMake. With MSYS2 on Windows, the default generator is “MinGW Makefiles”.

Determine the default CMake generator on Unix-like platforms:

cmake --system-information | awk '/^CMAKE_GENERATOR / {print substr($0, index($0,$2))}'

Determine the default CMake generator with PowerShell:

cmake --system-information | Select-String '^CMAKE_GENERATOR ' | % { ($_ -split '^CMAKE_GENERATOR\s+', 2)[1] }

If the environment doesn’t have a C or C++ compiler available, CMake might fail to determine the default generator. A missing compiler would likely only be an issue on Windows or minimal Linux / macOS / Unix environments.

On Unix-like platforms, there may be a working directory named “__cmake_systeminformation” created by CMake when running the above command. This directory can be deleted. To avoid using the current working directory on Unix-like platforms, run the above command in a temporary directory:

( cd "$(mktemp -d)" && cmake --system-information | awk '/^CMAKE_GENERATOR / {print substr($0, index($0,$2))}' )

A platform-independent, self-cleaning temporary directory can be used with Python:

import subprocess
import tempfile

with tempfile.TemporaryDirectory(ignore_cleanup_errors=True, delete=True) as temp_dir:
    result = subprocess.check_output(
        ['cmake', '--system-information'],
        cwd=temp_dir,
        text=True
    )
for line in result.splitlines():
    if line.startswith('CMAKE_GENERATOR '):
        default_generator = line.split(' ', 1)[1].strip().strip('"')
        print(default_generator)
        break

Related: detect CMake cached generator