I want to be able to set a bunch of boolean flags when calling CMake, that are later used in C code. Something like:
set(DEBUG_ENABLE false CACHE BOOL "enable debugging")
target_compile_definitions(target PRIVATE DEBUG_ENABLE=${DEBUG_ENABLE})
This actually works fine and produces something equivalent to:
#define DEBUG_ENABLE false
However, the the native CMake literals for BOOL
s are ON
/OFF
and tools like the CMake GUI will use those values, resulting in a define that doesn't work well in C :
#define DEBUG_ENABLE OFF
What is the best way to forward such a boolean variable from CMake to C ?
I can think of a few things:
- Conversion function in CMake, resulting in three lines per boolean value
- Use
STRING
instead ofBOOL
- Make it work in C :
#define ON true
None of these options seem particularly great to me.
CodePudding user response:
I'd use configure_file
. It won't get you a C bool
directly, but it's something that will actually scale over time.
You'll need to make a config file template for cmake to modify, in this example config.hpp.in
.
#cmakedefine01 DEBUG_ENABLE
Next, add a configure_file
line to your CMakeLists.txt
.
configure_file(config.hpp.in "${CMAKE_BINARY_DIR}/config.hpp")
Any variable in the config template will be replaced with either 0/1 depending on the value in cmake.
Working output:
(after configuring)
$ cat config.hpp
#define DEBUG_ENABLE 0
$ cmake -DDEBUG_ENABLE=ON .
-- Configuring done
-- Generating done
-- Build files have been written to: /tmp/so/cmake-bool/build
$ cat config.hpp
#define DEBUG_ENABLE 1
This also completely removes the need for your target_compile_definitions
line, provided you #include "config.hpp"
in the appropriate places.