如何使用CMake add_compile_definitions和list参数创建的宏?

neekobn8  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(42)

我的CMakeLists.txt文件的相关片段:

add_executable(hello main.cpp)
set(helloCompileOptions -Wall -Wextra -O3 -Wno-narrowing -ffast-math -march=native)
target_compile_options(hello PRIVATE ${helloCompileOptions})
target_compile_features(hello PUBLIC cxx_std_23)
add_compile_definitions(COMPILE_OPTIONS="${helloCompileOptions}")

字符串
会产生这些编译错误:

[build] <command line>:1:9: error: macro name must be an identifier
[build]     1 | #define -O3 1
[build]       |         ^
[build] <command line>:2:9: error: macro name must be an identifier
[build]     2 | #define -Wextra 1
[build]       |         ^
...


我应该如何处理helloCompileOptions列表,使它能够编译并作为字符串提供给我的C++代码?

pb3skfrl

pb3skfrl1#

使用CMake字符串处理:

add_executable(hello main.cpp)
set(compileOptions -Wall -Wextra -O3 -Wno-narrowing -ffast-math -march=native)
target_compile_options(hello PRIVATE ${compileOptions})
target_compile_features(hello PUBLIC cxx_std_23)
string(JOIN " " compileOptionsStr ${compileOptions})
target_compile_definitions(hello PUBLIC COMPILE_OPTIONS="${compileOptionsStr}")

字符串
使这条线:

cout << COMPILE_OPTIONS << "\n";


生产:

-Wall -Wextra -O3 -Wno-narrowing -ffast-math -march=native

相关问题