0

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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • Possible duplicate of [MSVC equivalent of gcc/clang's -Wall?](https://stackoverflow.com/questions/48568053/msvc-equivalent-of-gcc-clangs-wall) – Chris Turner Feb 01 '18 at 17:21
  • 1
    @ChrisTurner: No, that question is about which compiler switches are appropriate; this question is about how to set different properties with CMake. – einpoklum Feb 01 '18 at 17:22
  • Possible duplicate of [Modern way to set compiler flags in cross-platform cmake project](https://stackoverflow.com/questions/45955272/modern-way-to-set-compiler-flags-in-cross-platform-cmake-project) – Florian Feb 01 '18 at 20:16
  • @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 Feb 01 '18 at 20:41

2 Answers2

4

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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
3

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>
)
JengdiB
  • 56
  • 3