CMake conformance mode for MSVC

289 Views Asked by At

I develop in Linux and I am trying to test the project with MSVC.

Currently, I realize that MSVC is trying to compile the C++ project using the MSVC dialect of C++, and apparently, I have to force MSVC to compile in "conformance mode", I believe that I need to pass options like /std:c++17 /EHsc /permissive- /Zc:wchar_t /Zc:forScope /Zc:inline to the compiler.

I guess I can configure MSVC to pass these options, but a more elegant solution would be to set these options directly in the CMake, so I state these options for once.

What is the typical idiom to do this?

I for example used these, thinking that it will translate into MSVC into compiling with the conformant options, but it is not the case.

if (NOT DEFINED CMAKE_CXX_STANDARD)
    set(CMAKE_CXX_STANDARD 17)
endif()
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

(or the more modern target_compile_features(my_target INTERFACE cxx_std_17>))

I am using Version 17.6.5.

2

There are 2 best solutions below

4
alfC On

Ok, there might be no idiomatic way to do this.

target_compile_options(
  my_target PUBLIC
  $<$<CXX_COMPILER_ID:MSVC>: /permissive- /volatile:iso
  # /EHsc /Zc:wchar_t /Zc:forScope /Zc:inline  # might be necesssary for more compliance
  # /WX /W4 # if you want to add optimizations here
  >
)

Editorial note: it is silly that MS calls "permissive" to standard compliance. It is the opposite meaning. They had been permissive in the way they allowed highly non-standard codes.

It is "permissive-minus"! :)

1
andrewchan2022 On

my way:

if (MSVC)
   set(CXX_STANDARD "/std:c++latest")
   set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CXX_STANDARD} /std:c++17 /EHsc /permissive- /Zc:wchar_t /Zc:forScope /Zc:inline")
else()
    ...
endif()