5

How can I know in my CMakeLists.txt if I'm generating a Visual Studio solution or a Makefile?

I need to add external projects to the solution like this:

INCLUDE_EXTERNAL_MSPROJECT(cs-tests ${CMAKE_CURRENT_SOURCE_DIR}/cstests/cstests.csproj)

But I only want to do it when calling

cmake .. -DCMAKE_BUILD_TYPE=Debug -G "Visual Studio 12 2013"

not when I call:

cmake -G "NMake Makefiles" ..

2 Answers 2

16

CMake MSVC variable can be set even if the generator is other than Visual Studio (e.g. Ninja on Windows).

To check if CMake generator is Visual Studio (i.e. msbuild), the following did the trick:

if (CMAKE_GENERATOR MATCHES "Visual Studio")
    # Do Visual Studio specific stuff
else()
    # Other stuff
endif()
8

The name of the generator is stored in CMAKE_GENERATOR. It should contain the exact string given by the -G option.

The MSVC variable should also be set to TRUE, as should MSVC12 and MSVC_IDE (though I can't confirm that from the documentation at the moment.)

2
  • Note that MSVC is not set initially - it is likely set after the call to project. Meanwhile CMAKE_GENERATOR is always set within CMakeLists.txt - to a string such as "Visual Studio 15 2017 Win64". This is useful as setting CMAKE_TOOLCHAIN_FILE should be done before the call to project, but perhaps only on Windows; e.g. for vcpkg.cmake. Commented Aug 22, 2018 at 13:35
  • 1
    MSVC variable is not always defined, I recommend to match "if (CMAKE_GENERATOR MATCHES "Visual Studio")" Commented Feb 8, 2020 at 11:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.