title: CMake conditional preprocessor define on code
body: <p>I'm migrating a makefile project to CMake. The person who wrote the makefile the first time had done a module for writing certain values in an include file.</p>
  
  <p>There's a main config.h file that includes a config_in.h. The config.h file contains something like this:</p>
  
  <pre><code>#ifndef USE_FEATURE_A
  #define USE_FEATURE_A 0
  #endif
  
  #ifndef USE_FEATURE_B
  #define USE_FEATURE_B 0
  #endif
  </code></pre>
  
  <p>In the makefile there's a fake target like <code>with_feature_a</code> that writes in config_in.h </p>
  
  <pre><code>#define USE_FEATURE_A 1
  </code></pre>
  
  <p>In this way someone can type </p>
  
  <pre><code>make with_feature_a
  make
  </code></pre>
  
  <p>to get the right build.</p>
  
  <p>I want to replicate something like this using this codebase but using CMake.  I tried a couple of approaches suggested on the net, but I didn't get it to work.</p>
  
  <pre><code>set_target_properties(with_feature_a PROPERTIES COMPILE_DEFINITIONS 
      "WITH_FEATURE_A=1"
  )
  </code></pre>
  
  <p>This isn't working because if I run </p>
  
  <pre><code>make with_feature_a
  </code></pre>
  
  <p>I don't see <code>with_feature_a</code> in the preprocessor command line.</p>
  
  <p>The second attempt I made is to write a file directly with the content set to whatever I want, but I didn't understand how to connect the <code>file()</code> command to my target.</p>
  
  <p>I placed this in my CMakeLists.txt</p>
  
  <pre><code>file(WRITE 
  local/config_in.h 
      "#define WITH_FEATURE_A 1"
  )
  </code></pre>
  
  <p>but this isn't executed everytime and I don't know how to set it to a single target.</p>
  
  <p>Any help is appreciated. Thank you for reading all this stuff. Sorry for the long story :)</p>
  
  <p>UPDATE</p>
  
  <p>The solution provided <a href="https://stackoverflow.com/a/15212881/1350961">here</a> is a big enhacement on the road to solution. The problem is that is don't allow recursive definitions. I show an example:</p>
  
  <p>in CMakeLists.txt I placed:</p>
  
  <pre><code>if (WITH_FEATURE_A)
  MESSAGE(STATUS "WITH_FEATURE_A")
  add_definitions(-DUSE_FEATURE_A=1)
      add_definitions(-DWITH_FEABURE_B=1)
  endif()
  
  if (WITH_FEABURE_B)
  MESSAGE(STATUS "WITH_FEATURE_B")
  add_definitions(-DUSE_FEATURE_D=1)
  endif()
  
  
  if (WITH_FEABURE_C)
  MESSAGE(STATUS "WITH_FEATURE_C")
  add_definitions(-DUSE_FEATURE_D=1)
  endif()
  
  
  if (WITH_FEABURE_D)
  MESSAGE(STATUS "WITH_FEATURE_D")
  endif()
  </code></pre>
  
  <p>in this case if I execute cmake with -DWITH_FEATURE_A=1 I'd love to see in the output:</p>
  
  <pre><code>WITH_FEATURE_A
  WITH_FEATURE_B
  WITH_FEATURE_D
  </code></pre>
  
  <p>actually this code print just</p>
  
  <pre><code>WITH_FEATURE_A
  </code></pre>