CMake中经常需要判断当前操作系统,然后根据不同系统类型进行特定编译选项的控制,在CMake中判断当前操作系统类型有以下几种方法。

1 第一种方法

CMake 2.6以上判断可以使用以上内置变量

MESSAGE(STATUS "operation system is ${CMAKE_SYSTEM}")

IF (CMAKE_SYSTEM_NAME MATCHES "Linux")
    MESSAGE(STATUS "current platform: Linux ")
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "Windows")
    MESSAGE(STATUS "current platform: Windows")
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "Android")
    MESSAGE(STATUS "current platform: Android")
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "Darwin") 
    MESSAGE(STATUS "current platform: Mac OS X") 
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
    MESSAGE(STATUS "current platform: FreeBSD")
ELSE ()
    MESSAGE(STATUS "other platform: ${CMAKE_SYSTEM_NAME}")
ENDIF (CMAKE_SYSTEM_NAME MATCHES "Linux")

2 第二种方法

if(CMAKE_HOST_UNIX)
    MESSAGE(STATUS "current platform: Linux ")
elseif(CMAKE_HOST_WIN32)
    MESSAGE(STATUS "current platform: Windows")
else()
    MESSAGE(STATUS "other platform: ${CMAKE_SYSTEM_NAME}")
endif()

3 第三种方法

MESSAGE(STATUS "platform: ${CMAKE_SYSTEM_NAME}")
if (UNIX AND NOT APPLE)
    MESSAGE(STATUS "unix")
elseif (WIN32)
    MESSAGE(STATUS "windows")
elseif (APPLE)
    MESSAGE(STATUS "mac os")
else ()
    MESSAGE(STATUS "other platform")
endif ()