Browse Source

CMake: Enable /MP for MSVC toolchain

A new cache option named `CMake_MSVC_PARALLEL` is now available that can
be used to control the usage of [`/MP`][1] to the MSVC compiler. This
enables parallelized builds on a per-translation unit basis. To enable
`/MP`, specify value `ON` to the option. Using an integral non-zero
value will control the specific number of threads used with the `/MP`
option, as opposed to letting the toolchain decide for you.

Fixes #17696

[1]: https://docs.microsoft.com/en-us/cpp/build/reference/mp-build-with-multiple-processes
Robert Dailey 7 years ago
parent
commit
a1dee224b8
1 changed files with 23 additions and 0 deletions
  1. 23 0
      CompileFlags.cmake

+ 23 - 0
CompileFlags.cmake

@@ -82,3 +82,26 @@ endif ()
 if (CMAKE_ANSI_CFLAGS)
   set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_ANSI_CFLAGS}")
 endif ()
+
+# Allow per-translation-unit parallel builds when using MSVC
+if(CMAKE_GENERATOR MATCHES "Visual Studio" AND
+   (CMAKE_C_COMPILER_ID MATCHES "MSVC|Intel" OR
+   CMAKE_CXX_COMPILER_ID MATCHES "MSVC|Intel"))
+
+  set(CMake_MSVC_PARALLEL ON CACHE STRING "\
+Enables /MP flag for parallel builds using MSVC. Specify an \
+integer value to control the number of threads used (Only \
+works on some older versions of Visual Studio). Setting to \
+ON lets the toolchain decide how many threads to use. Set to \
+OFF to disable /MP completely." )
+
+  if(CMake_MSVC_PARALLEL)
+    if(CMake_MSVC_PARALLEL GREATER 0)
+      string(APPEND CMAKE_C_FLAGS " /MP${CMake_MSVC_PARALLEL}")
+      string(APPEND CMAKE_CXX_FLAGS " /MP${CMake_MSVC_PARALLEL}")
+    else()
+      string(APPEND CMAKE_C_FLAGS " /MP")
+      string(APPEND CMAKE_CXX_FLAGS " /MP")
+    endif()
+  endif()
+endif()