Reputation: 735
Visual Studio allows to select either the cl
compiler or the clang-cl
compiler to build projects -- these are called toolsets. These two compilers have different sets of flags, and in particular different flags for disabling warnings. Flags for one compiler produces errors on the other.
This problem can be solved in Visual Studio for both compilers at the same time by defining compiler flags conditionally based on the used toolset. Official documentation for that here.
I use CMake to generate the Visual Studio projects. How can I make CMake add such conditional flags for the generated Visual Studio projects?
Upvotes: 3
Views: 1750
Reputation: 1804
You can use CMAKE_CXX_COMPILER_ID
and CMAKE_CXX_SIMULATE_ID
with your favourite way of handling compilers (if-else or generator expressions)
Output for -T ClangCL
(Visual Studio 2019):
message(STATUS ${CMAKE_CXX_COMPILER_ID}) // Clang
message(STATUS ${CMAKE_CXX_SIMULATE_ID}) // MSVC
Output with no toolkit (Visual Studio 2019):
message(STATUS ${CMAKE_CXX_COMPILER_ID}) // MSVC
message(STATUS ${CMAKE_CXX_SIMULATE_ID}) // <empty>
Upvotes: 3
Reputation: 18243
Essentially a more modern approach to the earlier question here, you can use an if-statement to check the compiler type, and set compile flags based on that:
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
# Disable a Clang warning type.
target_compile_options(MyLib PRIVATE -Wno-unused-variable)
elseif(MSVC)
# Disable a MSVC warning type.
target_compile_options(MyLib PRIVATE /wd4101)
endif()
For putting this into a single expression, you can use CMake generator expressions (which are evaluated at the CMake buildsystem generation stage):
target_compile_options(MyLib PRIVATE
"$<IF:$<STREQUAL:${CMAKE_CXX_COMPILER_ID},Clang>,-Wno-unused-variable,/wd4101>"
)
For reference, here is a list of all of the clang warnings types.
Upvotes: 3