【问题标题】:CMake: add_compile_options() error with RELEASE/DEBUG configCMake:带有 RELEASE/DEBUG 配置的 add_compile_options() 错误
【发布时间】:2018-02-20 23:09:17
【问题描述】:

这有什么问题:

if(CMAKE_COMPILER_IS_GNUCXX OR MINGW OR ${CMAKE_CXX_COMPILER_ID} STREQUAL "Clang")
    add_compile_options("$<$<CONFIG:RELEASE>:-W -Wall -O3 -pedantic>")
    add_compile_options("$<$<CONFIG:DEBUG>:-W -Wall -O0 -g -pedantic>")
endif()

我明白了:

g++: error: unrecognized command line option ‘-W -Wall -O3 -pedantic’

如果我这样说,它会起作用:

if(CMAKE_COMPILER_IS_GNUCXX OR MINGW OR ${CMAKE_CXX_COMPILER_ID} STREQUAL "Clang")
    add_compile_options("$<$<CONFIG:RELEASE>:-W>")
    add_compile_options("$<$<CONFIG:RELEASE>:-Wall>")        
    add_compile_options("$<$<CONFIG:RELEASE>:-O3>")
    add_compile_options("$<$<CONFIG:RELEASE>:-pedantic>")
    add_compile_options("$<$<CONFIG:DEBUG>:-W>")
    add_compile_options("$<$<CONFIG:DEBUG>:-Wall>")
    add_compile_options("$<$<CONFIG:DEBUG>:-g>")
    add_compile_options("$<$<CONFIG:DEBUG>:-O0>")
    add_compile_options("$<$<CONFIG:DEBUG>:-pedantic>")
endif()

...但我想这不是故意的...

【问题讨论】:

    标签: cmake g++ ubuntu-16.04


    【解决方案1】:

    我已经尝试过您的示例,并且可以重现您的问题:

    c++: error: unrecognized command line option ‘-W -Wall -O3 -pedantic’
    

    add_compile_options() 命令将参数作为选项列表,因此您必须使用; 作为分隔符。

    以下在我的gcc/make 环境中确实有效:

    add_compile_options("$<$<CONFIG:RELEASE>:-W;-Wall;-O3;-pedantic>")
    add_compile_options("$<$<CONFIG:DEBUG>:-W;-Wall;-O0;-g;-pedantic>")
    

    或者写成:

    string(
        APPEND _opts
            "$<$<CONFIG:RELEASE>:-W;-Wall;-O3;-pedantic>"
            "$<$<CONFIG:DEBUG>:-W;-Wall;-O0;-g;-pedantic>"
    )
    add_compile_options("${_opts}")
    

    参考文献

    【讨论】:

    • 嗯...我很确定我已经尝试过了,但没有成功。请参阅 Tsyvarev 的回答。
    • @juzzlin 试了一下,它确实适用于我的 CMake 版本 3.10.2
    【解决方案2】:

    CMAKE_CXX_FLAGS 变量不同,该变量包含 单个 字符串和选项,用空格分隔,命令 add_compile_options 接受每个选项的分隔参数 .也就是说,如果没有生成器表达式,正确的用法是:

    add_compile_options("-W" "-Wall" "-O3" "-pedantic")
    

    因此,如果您想使用 生成器表达式,您需要将其附加到每个选项中,就像您在第二次尝试中所做的那样。

    如果您有许多每个配置选项,并且您发现 manual 为每个 tedios 重复生成器表达式,您可以创建一个简单的函数,它会为您执行此操作。喜欢这个:

    # add_compile_options_config(<CONFIG> <option> ...)
    function(add_compile_options_config CONFIG)
        foreach(opt ${ARGN})
            add_compile_options("$<$<CONFIG:${CONFIG}>:${opt}>")
        endforeach()
    endfunction()
    

    有用法:

    add_compile_options_config(RELEASE "-W" "-Wall" "-O3" "-pedantic")
    add_compile_options_config(DEBUG "-W" "-Wall" "-O0" "-g" "-pedantic")
    

    如果您想以特定于配置的方式将“-W”、“-O3”等编译器选项添加到项目中的所有目标,请考虑使用CMAKE_CXX_FLAGS_ 变量:

    string(APPEND CMAKE_CXX_FLAGS_RELEASE " -W -Wall -03 -pedantic")
    

    【讨论】:

    • 在您的示例中调用 add_compile_options 而不是新的 add_compile_options_config 是有意还是错字?
    • 这是一个错字,现已修正。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 2019-12-29
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    相关资源
    最近更新 更多