CMake - integrating options into C++ source files
c++, c-preprocessor, cmake, configure
Solution
You may combine `option` and `add_definitions` of cmake like here. Since a simple example is clearer than a long text here is a little main.c :
#include<stdio.h>
int main(int argc, char *argv[])
{
printf("start\n");
#ifdef USE_DEBUG
printf("Using debug\n");
#endif
printf("end\n");
return 0;
}
The CMakeLists.txt is :
cmake_minimum_required (VERSION 2.6)
project (HELLO)
option(WITH_DEBUG "Use debug" OFF)
if (WITH_DEBUG)
MESSAGE(STATUS "WITH_DEBUG")
add_definitions(-DUSE_DEBUG)
endif()
add_executable (main main.c)
You can try it by typing `cmake .` or `cmake . -DWITH_DEBUG=ON` then `make` and `./main`
Problem
I'm working with an existing project and cleaning up the CMake for it. However, right now I'm a bit confused by how exactly to go about integrating the CMake options into the actual source code. For simplicity's sake, let's say I'd like to only execute one chunk of code, let's say `cout << "print";`, inside `example.cpp` if, on CMake, the value `ENABLE_PRINT` is set to `ON`. The project directory will look like this: Using the above example, I did the following: - On the parent project `CMakeLists.txt`, I added `OPTION( ENABLE_PRINT "Enable Print" ON)` - Then, on the example subproject source folder `Config.h` file, I added `#define ENABLE_PRINT` - On the `Config.h.in` located in the example subproject, I added `#cmakedefine ENABLE_PRINT` - Finally, on the source file `example.cpp`, I encircled `cout << "print";` inside `#ifdef ENABLE_PRINT` and `#endif` After making those changes, the project will configure and generate just fine. However, when I make the software, it will error and essentially tell me that the chunk of code I encircled with `#ifdef` was not executed at all; it was ignored. In other words, the above steps I took did not do anything except "comment out" the chunk of code I wanted to make conditional upon ENABLE_PRINT. So, how would I make this work?