oarfish
oarfish

Reputation: 4621

How can I use cmake generator expressions for adding compiler flags for different compilers?

I'm trying to use something like this with CMAKE 3.17.2:

# GCC options
add_compile_options($<$<CXX_COMPILER_ID:GNU>:-fmax-errors=1>)

# clang options
add_compile_options($<$<CXX_COMPILER_ID:AppleClang>:-ferror-limit=2,-Werror=unused-private-field>)

However, It seems to be impossible to add multiple options at the same time; i have tried with commas, spaces, quote-enclosing the options. Is there syntax that allows this or must every option be added individually?

Upvotes: 2

Views: 458

Answers (1)

nop666
nop666

Reputation: 603

I think semi-colon is the way to go. Here is an example of nested conditions with multiple options:

set(MY_COMPILE_OPTIONS
    "$<IF:$<CXX_COMPILER_ID:MSVC>,"
        "/W4;$<$<CONFIG:RELEASE>:/O2>,"
        "-Wall;-Wextra;-Werror;"
            "$<$<CONFIG:RELEASE>:-O3>"
    ">"
)

target_compile_options(MyTarget PUBLIC "${MY_COMPILE_OPTIONS}")

This means:

  • If MSVC && !Release build -> /W4
  • If MSVC && Release build -> /W4 /02
  • Else if !Release build -> -Wall -Wextra -Werror
  • Else if Release build -> -Wall -Wextra -Werror -O3

Upvotes: 2

Related Questions