0

I have a header file which overrides malloc with a macro. Using add_definitions(-include ../include/failing-malloc-test.h) I'm able to force cmake to include this header file in all targets. The problem is that I only want to have my header file included in some targets(test targets and so on). I tried achieving this using target_compile_definition, but I couldn't achieve the same effect, because target_compile_definition seems to work different than add_definitions. Currently the only solution that I can think of is duplicating all source files and adding the #include "failing-malloc-test.h" manually - what I obviously want to avoid doing.

QuesterDesura
  • 385
  • 2
  • 18
  • Have you tried adding [properties](https://cmake.org/cmake/help/latest/manual/cmake-properties.7.html#properties-on-source-files) to the specific source files? Specifically, the `COMPILE_FLAGS`. – John Jan 18 '18 at 13:42
  • No, I didn't knew about that one. I'm pretty new to cmake. I will take a look at this, thanks. – QuesterDesura Jan 18 '18 at 13:43
  • Using `SET_TARGET_PROPERTIES (main PROPERTIES COMPILE_FLAGS "-include ../include/failing-malloc-test.h")` I have solved my problem! Thanks for hinting me to the properties stuff! If you want go ahead and post it as an answer and I will accept it. – QuesterDesura Jan 18 '18 at 13:55
  • Consider to use `target_compile_options` instead of `target_compile_definitions` -- this is the "modern" way to solve your issue. – zaufi Jan 18 '18 at 15:20
  • Related but not the same: [cmake include header into every source file](/q/32773283/11107541). – starball Jan 19 '23 at 01:21

1 Answers1

2

CMake has a properties-based mechanism. You can assign to properties on targets, source files, and other parts. Working with targets is the usual and default action, so a whole family of target_* commands are provided for setting properties on targets. If you want to add a compile option for all sources in a specific target then use target_compile_options. Do not use the COMPILE_DEFINITIONS property for other options than defining pre-processor symbols. So you be able to get what you want with

target_compile_options(<my-test-target> "-include ../include/failing-malloc-test.h")
John
  • 7,301
  • 2
  • 16
  • 23
  • 2
    And of course this will only work on toolchains supporting the `-include` option, essentially rendering your build non-portable. Be mindful of this! – ComicSansMS Jan 19 '18 at 10:34