einpoklum
einpoklum

Reputation: 132260

Setting platform-specific / compiler-specific target properties with CMake

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.

Upvotes: 0

Views: 1811

Answers (2)

JengdiB
JengdiB

Reputation: 56

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>
)

Upvotes: 3

einpoklum
einpoklum

Reputation: 132260

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.

Upvotes: 4

Related Questions