Setting the MSVC runtime in CMake

前端 未结 4 830
独厮守ぢ
独厮守ぢ 2020-12-04 17:34

I\'m following the instructions in the CMake FAQ entry \"How can I build my MSVC application with a static runtime?\" to centralize selection of the MSVC runtime for a bunch

4条回答
  •  旧时难觅i
    2020-12-04 18:35

    Here is a solution that I came up with, which should work for CMake versions before and after 3.15.

    # This logic needs to be considered before project()
    set(_change_MSVC_flags FALSE)
    if(WIN32)
      if(CMAKE_VERSION VERSION_LESS 3.15.0)
        set(_change_MSVC_flags TRUE)
      else()
        # Set MSVC runtime to MultiThreaded (/MT)
        cmake_policy(SET CMP0091 NEW)
        set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>")
      endif()
    endif()
    
    project(MyProj ....)
    
    if(_change_MSVC_flags)
      # Modify compile flags to change MSVC runtime from /MD to /MT
      set(_re_match "([\\/\\-]M)D")
      set(_re_replace "\\1T")
      string(REGEX REPLACE ${_re_match} ${_re_replace}
        CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
      string(REGEX REPLACE ${_re_match} ${_re_replace}
        CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}")
      string(REGEX REPLACE ${_re_match} ${_re_replace}
        CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}")
      string(REGEX REPLACE ${_re_match} ${_re_replace}
        CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL}")
      string(REGEX REPLACE ${_re_match} ${_re_replace}
        CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO}")
    endif()
    

    If other languages are used (i.e. C), then these would also need to be added too.

提交回复
热议问题