Force build to conform C++ standard on windows by adding /permissive- flag (#149035)

Fixes #147366

1. Add `/permissive-` to the `torch_compile_options` for the build to conform to the C++ standard.
2. Fix the error when trying to assign a string literal to a non-const ptr.

The `/permissive-` flag can be found at https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170

From the above [doc](https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170#remarks),
>  By default, the /permissive- option is set in new projects created by Visual Studio 2017 version 15.5 and later versions.
> The /permissive- option is implicitly set by the /std:c++latest option starting in Visual Studio 2019 version 16.8, and in version 16.11 by the /std:c++20 option.

Thus, it is reasonable to add this flag to the existing project.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/149035
Approved by: https://github.com/guangyey, https://github.com/malfet
This commit is contained in:
Su, Tong
2025-03-18 01:51:46 +00:00
committed by PyTorch MergeBot
parent c1dd75e4dc
commit 60523540f1
3 changed files with 11 additions and 4 deletions

View File

@ -1059,9 +1059,6 @@ if(USE_XPU)
add_library(torch_xpu ${Caffe2_XPU_SRCS})
torch_compile_options(torch_xpu) # see cmake/public/utils.cmake
target_compile_definitions(torch_xpu PRIVATE USE_XPU)
if(WIN32)
target_compile_options(torch_xpu PRIVATE /permissive-)
endif()
# ATen XPU implementation
set(TORCH_XPU_OPS_DIR ${TORCH_ROOT}/third_party/torch-xpu-ops)

View File

@ -361,6 +361,16 @@ function(torch_compile_options libname)
set(MSVC_DEBINFO_OPTION "/Zi")
endif()
if(${MSVC_TOOLSET_VERSION} GREATER_EQUAL 142)
# Add /permissive- flag for conformance mode to the compiler.
# This will force more strict check to the code standard.
# 1. From MS official doc: https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170#remarks
# By default, the /permissive- option is set in new projects created by Visual Studio 2017 version 15.5 and later versions.
# We set the /permissive- flag from VS 2019 (MSVC_TOOLSET_VERSION 142) to avoid compiling issues for old toolkit.
# 2. For MSVC VERSION: https://cmake.org/cmake/help/latest/variable/MSVC_TOOLSET_VERSION.html
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /permissive-" PARENT_SCOPE)
endif()
target_compile_options(${libname} PUBLIC
$<$<COMPILE_LANGUAGE:CXX>:
${MSVC_RUNTIME_LIBRARY_OPTION}

View File

@ -145,7 +145,7 @@ static void activate() {
intptr_t run(const std::string& cmd) {
// Getting the path of `cmd.exe`
wchar_t* comspec = _wgetenv(L"COMSPEC");
const wchar_t* comspec = _wgetenv(L"COMSPEC");
if (!comspec) {
comspec = L"C:\\Windows\\System32\\cmd.exe";
}