0
votes

I'm working on a C project whose CMakeLists.txt has the following:

set_property(
    TARGET foo
    APPEND PROPERTY COMPILE_OPTIONS -Wall
)

This was fine as long as I could assume the compiler would be gcc or clang, which I was assuming. But - for MSVC, -Wall means something else and undesirable, so I want to set other switches. How can I / how should I go about doing this?

Note: I'm not asking which compiler options to use, I'm asking how to apply my choices of flags (or any other property) using CMake.

2
@ChrisTurner: No, that question is about which compiler switches are appropriate; this question is about how to set different properties with CMake. - einpoklum
@Florian: Not a dupe, since that question is mostly about setting up multiple builds for multiple compilers in the same directory (the third point out of three there, but being the most important). - einpoklum

2 Answers

4
votes

One way to do it might be something line:

if ("${CMAKE_C_COMPILER_ID}" STREQUAL "Clang")
  set_property(TARGET foo APPEND PROPERTY COMPILE_OPTIONS -Wall)
elseif ("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU")
  set_property(TARGET foo APPEND PROPERTY COMPILE_OPTIONS -Wall)
elseif ("${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC")
  set_property(TARGET foo APPEND PROPERTY COMPILE_OPTIONS /W3)

and the list of compiler IDs is here.

2
votes

Another way is to use target_compile_options along with generator expression. For ex.

add_library(foo foo.cpp)
target_compile_options(foo
    PRIVATE
        $<$<CXX_COMPILER_ID:MSVC>:/W3>
        $<$<CXX_COMPILER_ID:Clang>:-Wall>
        $<$<CXX_COMPILER_ID:GNU>:-Wall>
)