为多个目标(CMake)重用变量中的 target_compile_options

agg*_*sol 1 cmake

我有几个构建目标,并希望设置相同的编译选项集,如下所示:

set(app_compile_options "-Wall -Wextra -Wshadow -Wnon-virtual-dtor \
    -Wold-style-cast \
    -Woverloaded-virtual -Wzero-as-null-pointer-constant \
    -pedantic -fPIE -fstack-protector-all -fno-rtti")

add_executable(foo foo.cpp)
target_compile_options(foo PUBLIC ${app_compile_options})

add_executable(bar bar.cpp)
target_compile_options(bar PUBLIC ${app_compile_options})
Run Code Online (Sandbox Code Playgroud)

编译时出现以下错误:

error: unrecognized command line option ‘-Wall -Wextra -Wshadow -Wnon-virtual-dtor -Wold-style-cast     -Woverloaded-virtual -Wzero-as-null-pointer-constant     -pedantic -fPIE -fstack-protector-all -fno-rtti’
Run Code Online (Sandbox Code Playgroud)

我是否需要另一种格式或特殊语法来定义变量中的编译选项?

squ*_*les 5

您可以使用引号将选项作为单个字符串传递。尝试删除引号(和\行继续标记)以将编译选项作为列表传递:

set(app_compile_options -Wall -Wextra -Wshadow -Wnon-virtual-dtor
    -Wold-style-cast
    -Woverloaded-virtual -Wzero-as-null-pointer-constant
    -pedantic -fPIE -fstack-protector-all -fno-rtti
)
Run Code Online (Sandbox Code Playgroud)


Gui*_*cot 5

除了@squaresstkittles 的回答之外,我还要补充一点,您可以为此目的使用接口目标:

add_library(common INTERFACE)

target_compile_options(common INTERFACE
    -Wall -Wextra -Wshadow -Wnon-virtual-dtor
    -Wold-style-cast
    -Woverloaded-virtual -Wzero-as-null-pointer-constant
    -pedantic -fPIE -fstack-protector-all -fno-rtti
)

target_link_libraries(foo PRIVATE common)
target_link_libraries(bar PRIVATE common)
Run Code Online (Sandbox Code Playgroud)