Platform detection in CMake
Here's an expanded version of KneLL's answer, also checking for Windows 10.
if(WIN32)
macro(get_WIN32_WINNT version)
if(CMAKE_SYSTEM_VERSION)
set(ver ${CMAKE_SYSTEM_VERSION})
string(REGEX MATCH "^([0-9]+).([0-9])" ver ${ver})
string(REGEX MATCH "^([0-9]+)" verMajor ${ver})
# Check for Windows 10, b/c we'll need to convert to hex 'A'.
if("${verMajor}" MATCHES "10")
set(verMajor "A")
string(REGEX REPLACE "^([0-9]+)" ${verMajor} ver ${ver})
endif()
# Remove all remaining '.' characters.
string(REPLACE "." "" ver ${ver})
# Prepend each digit with a zero.
string(REGEX REPLACE "([0-9A-Z])" "0\\1" ver ${ver})
set(${version} "0x${ver}")
endif()
endmacro()
get_WIN32_WINNT(ver)
add_definitions(-D_WIN32_WINNT=${ver})
endif()
As karlphilip pointed out, you can use if(WIN32)
for platform detection.
You'll have a number of possibilities for passing preprocessor defines to the application:
- Use a configure header that gets preprocessed by CMake's configure_file. This approach has the advantage that all
#define
s are actually part of the code and not of the build environment. The disadvantage is that it requires an (automatic) preprocessing step by CMake - Use add_definitions. This will add the preprocessor flag for all source files in the project, so it's more of a quick and dirty approach.
Use the COMPILE_DEFINITIONS property. This allows fine grained control over the defines on a per-file (and even per-config) basis:
set_property(SOURCE ${YOUR_SOURCE_FILES} APPEND PROPERTY COMPILE_DEFINITIONS YOUR_FLAG1 YOUR_FLAG2)
In modern CMake versions (2.8.12 and higher) you can also use the more convenient
target_compile_definitions
command for this.
I usually prefer the latter, but that's mostly a matter of personal taste.
Inside the CMakeLists.txt file you can do:
IF (WIN32)
# set stuff for windows
ELSE()
# set stuff for other systems
ENDIF()
Here is a simple solution.
macro(get_WIN32_WINNT version)
if (WIN32 AND CMAKE_SYSTEM_VERSION)
set(ver ${CMAKE_SYSTEM_VERSION})
string(REPLACE "." "" ver ${ver})
string(REGEX REPLACE "([0-9])" "0\\1" ver ${ver})
set(${version} "0x${ver}")
endif()
endmacro()
get_WIN32_WINNT(ver)
add_definitions(-D_WIN32_WINNT=${ver})