简体   繁体   中英

CMake: add conditional compiler flags into Visual Studio project

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?

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM