How do I define a preprocessor variable through CMake?
The equivalent code would be #define foo
.
This question is related to
c++
cmake
c-preprocessor
The other solution proposed on this page are useful some versions of Cmake <
3.3.2
. Here the solution for the version I am using (i.e.,3.3.2
). Check the version of your Cmake by using$ cmake --version
and pick the solution that fits with your needs. The cmake documentation can be found on the official page.
With CMake version 3.3.2, in order to create
#define foo
I needed to use:
add_definitions(-Dfoo) # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)
and, in order to have a preprocessor macro definition like this other one:
#define foo=5
the line is so modified:
add_definitions(-Dfoo=5) # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)
To do this for a specific target, you can do the following:
target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)
You should do this if you have more than one target that you're building and you don't want them all to use the same flags. Also see the official documentation on target_compile_definitions.
Source: Stackoverflow.com