CMake generator expression, differentiate C / C++ code

后端 未结 3 1271
情书的邮戳
情书的邮戳 2020-12-30 03:32

I would like to add -std=c++11 to my

add_compile_options(\"-std=c++11\")

However, this also adds them to compilation of C

3条回答
  •  自闭症患者
    2020-12-30 03:57

    When you have mixed C and C++ sources, the LINKER_LANGUAGE property might apply the wrong flags for compilation of individual sources. The solution is to use the COMPILE_LANGUAGE generator expression (introduced with CMake 3.3). The simplest example for your original C++1x flag is:

    add_compile_options($<$:-std=c++11>)
    

    When you have a string of compile options (for example, for usage with the COMPILE_FLAGS target property), you have to split the flags

    set(WARNCFLAGS "-Wall -Wextra -Wfuzzle -Wbar")
    # ...
    string(REPLACE " " ";" c_flags "${WARNCFLAGS}")
    string(REPLACE " " ";" cxx_flags "${WARNCXXFLAGS} ${CXX1XCXXFLAGS}")
    add_compile_options(
      "$<$:${c_flags}>"
      "$<$:${cxx_flags}>"
    )
    # Two alternative variants for single targets that take strings:
    target_compile_options(some-target PRIVATE "${WARNCFLAGS}")
    set_target_properties(some-target PROPERTIES
      COMPILE_FLAGS "${WARNCFLAGS}")
    

    Use of strings is however deprecated in favor of lists. When lists are in use, you can use:

    set(c_flags -Wall -Wextra -Wfuzzle -Wbar)
    # ...
    add_compile_options(
      "$<$:${c_flags}>"
      "$<$:${cxx_flags}>"
    )
    # Two alternative variants for single targets given a list:
    target_compile_options(some-target PRIVATE ${f_flags})
    set_target_properties(some-target PROPERTIES
      COMPILE_OPTIONS "${c_flags}")
    

    Pay attention to the quoting. If a list is not quotes, it is expanded to its items (and is no longer a list). To pass a list between commands, quote it.

提交回复
热议问题