CMake: Fix selection of MSVC Runtime compile flags #1663
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
My last attempt at solving this was not correct, and I apologise for that.
MSVC Runtime Selection
There are two main ways to set the msvc runtime library; Using
target_compile_options()
to add the flags or using theCMAKE_MSVC_RUNTIME_LIBRARY
property abstraction1, introduced in CMake version 3.15 with the policy CMP00912 toremove the flags from
CMAKE_<LANG>_FLAGS_<CONFIG>
.Default:
CMAKE_MSVC_RUNTIME_LIBRARY="MultiThreaded$<$<CONFIG:Debug>:Debug>DLL"
This initializes each target's
MSVC_RUNTIME_LIBRARY
property at the time of target creation.This creates a conundrum for us, the
CMAKE_MSVC_RUNTIME_LIBRARY
needs to be correct at the time the target is created, but we have no control over the consumers CMake scripts, and the per-targetMSVC_RUNTIME_LIBRARY
propertyis not transient, that is, it doesn't flow to dependent targets.
The previous attempt using INTERFACE_MSVC_RUNTIME_LIBRARY was a complete brain fail on my part, the INTERFACE_ prefix is not a universal concept like I thought it was, this property will do nothing.
We need
CMAKE_MSVC_RUNTIME_LIBRARY
to be"$<1:>"
3 to ensure it will not add any flags. And then usetarget_compile_options()
so that our flags will propagate to consumers.In the interests of playing nicely we detect whether we are being consumed and notify the consumer that we are setting
CMAKE_MSVC_RUNTIME_LIBRARY
, that dependent targets rely on it, and point them to these comments as to why.Further information from the cmake forum
Footnotes
https://cmake.org/cmake/help/latest/policy/CMP0091.html ↩
https://cmake.org/cmake/help/latest/variable/CMAKE_MSVC_RUNTIME_LIBRARY.html ↩
This is a generator expression that results in the empty string. ↩