-->

Replacing /MD with /MT in CMake is not possible in

2019-08-18 11:28发布

问题:

I have a C++ library which I want to compile it using Visual Studio 2017 (CMake/Ninja) with /MT compiler option in Release mode. Here, I asked a similar question some time before. The answer to that question helped but causes the compiler to complain (report warning) about overriding /MD with /MT. Then I used this solution, but setting the CMAKE_CXX_FLAGS_RELEASE has no effect on the compiler command line arguments in Release mode. I mean the following code works well in Debug mode:

set(CompilerFlags
    CMAKE_CXX_FLAGS
    CMAKE_CXX_FLAGS_DEBUG
    CMAKE_CXX_FLAGS_RELEASE)
foreach(CompilerFlag ${CompilerFlags})
    message("before replace: " ${${CompilerFlag}})
    string(REPLACE "/MD" "/MT" ${CompilerFlag} "${${CompilerFlag}}")
    message("after replace: " ${${CompilerFlag}})
endforeach()

The result of running CMake would be:

before replace: /DWIN32 /D_WINDOWS /W3 /GR /EHsc
after replace: /DWIN32 /D_WINDOWS /W3 /GR /EHsc
before replace: /MDd /Zi /Ob0 /Od /RTC1
after replace: /MTd /Zi /Ob0 /Od /RTC1
before replace: /MD /O2 /Ob2 /DNDEBUG
after replace: /MT /O2 /Ob2 /DNDEBUG

The result of build would be:

cl.exe  ... /MTd ...

In Release mode the result of running CMake would be the same; however, the result of build would be:

cl.exe  ... /MD ...

If you know what's the correct way of doing that, I'll be really appreciate to hear that.

回答1:

it works after long struggling

TARGET_COMPILE_OPTIONS(${library_name} PRIVATE "/MT$<$<CONFIG:Release>:>")