How do I use macros created with CMake add_compile_definitions and list argument?

48 Views Asked by At

A relevant fragment of my CMakeLists.txt file:

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}")

produces these compilation errors:

[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]       |         ^
...

How should I handle the helloCompileOptions list, so it compiles and is avalable as a string to my C++ code?

1

There are 1 best solutions below

0
Paul Jurczak On

Using CMake string processing:

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}")

makes this line:

  cout << COMPILE_OPTIONS << "\n";

produce:

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