54

How can I pass a macro to the preprocessor? For example, if I want to compile some part of my code because a user wants to compile unit test, I would do this:

#ifdef _COMPILE_UNIT_TESTS_
    BLA BLA
#endif //_COMPILE_UNIT_TESTS_

Now I need to pass this value from CMake to the preprocessor. Setting a variable doesn't work, so how can I accomplish this?

4444
  • 3,541
  • 10
  • 32
  • 43
Killrazor
  • 6,856
  • 15
  • 53
  • 69

2 Answers2

65

add_definitions(-DCOMPILE_UNIT_TESTS) (cf. CMake's doc) or modify one of the flag variables (CMAKE_CXX_FLAGS, or CMAKE_CXX_FLAGS_<configuration>) or set COMPILE_FLAGS variable on the target.

Also, identifiers that begin with an underscore followed by an uppercase letter are reserved for the implementation. Identifiers containing double underscore, too. So don't use them.

BenC
  • 8,729
  • 3
  • 49
  • 68
Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • 18
    Can also be done from the command line a la `cmake .. -DCOMPILE_UNIT_TESTS` – dantswain Mar 09 '12 at 19:07
  • 13
    @dantswain: That sets CMake cache variable. – Cat Plus Plus Mar 09 '12 at 19:08
  • 5
    To add a definition only to specific targets, use [COMPILE_DEFINITIONS](http://www.cmake.org/cmake/help/cmake-2-8-docs.html#prop_dir:COMPILE_DEFINITIONS). For example: `set_target_properties(target1 target2 PROPERTIES COMPILE_DEFINITIONS "COMPILE_UNIT_TESTS")` – Lesque Mar 09 '12 at 20:27
  • 8
    Or [target_compile_definitions](http://www.cmake.org/cmake/help/v3.0/command/target_compile_definitions.html) in CMake 3.0 – lisyarus Aug 19 '14 at 15:20
  • Ugh ... "organically grown" build systems without uniform support across platforms are really a pain. Never know which one is the right option. Besides, how do I express _undefining_ a preprocessor symbol? – 0xC0000022L Sep 09 '19 at 08:01
22

If you have a lot of preprocessor variables to configure, you can use configure_file:

Create a configure file, eg. config.h.in with

#cmakedefine _COMPILE_UNIT_TESTS_
#cmakedefine OTHER_CONSTANT
...

then in your CMakeLists.txt:

set(_COMPILE_UNIT_TESTS_ ON CACHE BOOL "Compile unit tests") # Configurable by user 
set(OTHER_CONSTANT OFF) # Not configurable by user
configure_file(config.h.in config.h)

in the build directory, config.h is generated:

#define _COMPILE_UNIT_TESTS_
/* #undef OTHER_CONSTANT */

As suggested by robotik, you should add something like include_directories(${CMAKE_CURRENT_BINARY_DIR}) to your CMakeLists.txt for #include "config.h" to work in C++.

Community
  • 1
  • 1
Lesque
  • 773
  • 8
  • 16
  • 1
    @robotik suggests that you need `include_directories(${PROJECT_BINARY_DIR})` or else CMake will not bea ble to find the generated `config.h`. – drs Aug 21 '14 at 12:49