Merge topic 'vs-lang-flags' into release-3.18

c4109a1bc8 VS: Restore toleration of target-wide -TP flag with MSVC

Acked-by: Kitware Robot <kwrobot@kitware.com>
Merge-request: !5051
diff --git a/Source/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx
index a3ccd2b..a8e424d 100644
--- a/Source/cmVisualStudio10TargetGenerator.cxx
+++ b/Source/cmVisualStudio10TargetGenerator.cxx
@@ -2884,6 +2884,12 @@
     clOptions.RemoveFlag("SpectreMitigation");
   }
 
+  // Remove any target-wide -TC or -TP flag added by the project.
+  // Such flags are unnecessary and break our model of language selection.
+  if (langForClCompile == "C" || langForClCompile == "CXX") {
+    clOptions.RemoveFlag("CompileAs");
+  }
+
   this->ClOptions[configName] = std::move(pOptions);
   return true;
 }
diff --git a/Tests/SetLang/CMakeLists.txt b/Tests/SetLang/CMakeLists.txt
index f24e5cb..9de4fc6 100644
--- a/Tests/SetLang/CMakeLists.txt
+++ b/Tests/SetLang/CMakeLists.txt
@@ -8,3 +8,10 @@
 set_source_files_properties(foo.c bar.c PROPERTIES LANGUAGE CXX)
 target_link_libraries(SetLang foo)
 set_target_properties(SetLang PROPERTIES LINKER_LANGUAGE CXX)
+
+# VS generators historically tolerated target-wide -TP flags added
+# by project code, so cover that case to preserve the behavior.
+if(CMAKE_GENERATOR MATCHES "^Visual Studio" AND "x${CMAKE_C_COMPILER_ID}" STREQUAL "xMSVC")
+  add_library(stay stay_c.c stay_cxx.cxx)
+  set_property(TARGET stay PROPERTY COMPILE_OPTIONS "-TP")
+endif()
diff --git a/Tests/SetLang/stay_c.c b/Tests/SetLang/stay_c.c
new file mode 100644
index 0000000..70755f3
--- /dev/null
+++ b/Tests/SetLang/stay_c.c
@@ -0,0 +1,8 @@
+#ifdef __cplusplus
+#  error C source incorrectly compiled as C++
+#endif
+
+int stay_c(void)
+{
+  return 0;
+}
diff --git a/Tests/SetLang/stay_cxx.cxx b/Tests/SetLang/stay_cxx.cxx
new file mode 100644
index 0000000..e035260
--- /dev/null
+++ b/Tests/SetLang/stay_cxx.cxx
@@ -0,0 +1,8 @@
+#ifndef __cplusplus
+#  error C++ source incorrectly compiled as C
+#endif
+
+int stay_cxx()
+{
+  return 0;
+}