How to detect if the CMake script is being run in MSYS2 environment?

Viewed 1382

I want to detect if the CMakeLists.txt is being summoned inside an MSYS2 environment/shell:

$ uname
MSYS_NT-10.0-18363

from here I have tried:

cmake_minimum_required(VERSION 3.10)

project(test_cmake)

if(MSYS) # yes I have also tried MSYS2 with the same result!
    message("This is MSYS")
else()
    message("This is not MSYS")
endif()

which returns the same result This is not MSYS both in Windows cmd and MSYS2 shell. I'm not actually surprised because MSYS2 and MSYS are two different beasts! Also from here, I tried:

message(${CMAKE_SYSTEM_NAME})

which both in cmd and MSYS2 returns Windows! I would appreciate it if you could help me know how I can detect if the cmake command is being run from inside an MSYS2 shell. Thanks for your support in advance.

P.S.1. As a personal note for myself, this and this seem like good sources to look into.

P.S.2 Strangely enough the command

message(${CMAKE_HOST_SYSTEM_NAME})

also returns Windows while on my MSYS2, according to the docuemntation, it must return the result of uname -s!

4 Answers

OK, I think I know where the problem comes from. As I also had other issues earlier, the mingw64/mingw-w64-x86_64-cmake caused this problem. So I uninstalled it and installed the msys/cmake package. Now:

  • if(MSYS) retruns TRUE
  • message(${CMAKE_SYSTEM_NAME}) --> MSYS
  • message(${CMAKE_SYSTEM}) --> MSYS-3.0.7-338.x86_64
  • message(${CMAKE_HOST_SYSTEM_NAME}) --> MSYS

one caveat is that now you have to specify the path to the make tool by -D CMAKE_MAKE_PROGRAM:path=mingw32-make

I think there should be a better answer, but you can use the output from uname you presented:

execute_process(COMMAND uname OUTPUT_VARIABLE uname)
if (uname MATCHES "^MSYS")

What I found most reliable, considering all answers and comments up to now, and building upon them, is using

execute_process(COMMAND uname OUTPUT_VARIABLE uname)
if (uname MATCHES "^MSYS" OR uname MATCHES "^MINGW")
    message("This is MSYS")
else()
    message("This is not MSYS")
endif()

In my msys2, this is what I see in cmake

message("a ${MSYS}")                    --> prints a, MSYS does not exist 
message("a ${CMAKE_SYSTEM_NAME}")       --> prints a, CMAKE_SYSTEM_NAME does not exist 
message("a ${CMAKE_SYSTEM}")            --> prints a, CMAKE_SYSTEM does not exist 
message("a ${CMAKE_HOST_SYSTEM_NAME}")  --> prints a MSYS_NT-10.0-19044-WOW64, could be used

and

$ uname
MSYS_NT-10.0-19044-WOW64
Related