Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define preprocessor macro through CMake?

How do I define a preprocessor variable through CMake?

The equivalent code would be #define foo.

like image 694
Mythli Avatar asked Jan 26 '12 11:01

Mythli


People also ask

How does CMake define preprocessor?

If you are using CMake 3. X your first choice for adding a preprocessor macro should be target_compile_definitions. The reason you should prefer this approach over any other approach is because it granularity is target based. IE the macro will only be added to your exe/library.

What is Ifdef C++?

The #ifdef identifier statement is equivalent to #if 1 when identifier has been defined. It's equivalent to #if 0 when identifier hasn't been defined, or has been undefined by the #undef directive.


2 Answers

For a long time, CMake had the add_definitions command for this purpose. However, recently the command has been superseded by a more fine grained approach (separate commands for compile definitions, include directories, and compiler options).

An example using the new add_compile_definitions:

add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION}) add_compile_definitions(WITH_OPENCV2) 

Or:

add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION} WITH_OPENCV2) 

The good part about this is that it circumvents the shabby trickery CMake has in place for add_definitions. CMake is such a shabby system, but they are finally finding some sanity.

Find more explanation on which commands to use for compiler flags here: https://cmake.org/cmake/help/latest/command/add_definitions.html

Likewise, you can do this per-target as explained in Jim Hunziker's answer.

like image 136
ypnos Avatar answered Sep 22 '22 18:09

ypnos


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.

like image 45
Jim Hunziker Avatar answered Sep 24 '22 18:09

Jim Hunziker