CMake: when to use add_definitions instead of set_target_properties(target PROPERTIES COMPILE_DEFINITIONS definitions)

add_definitions has existed in CMake since the very first build of CMake came online more than a decade ago.

COMPILE_DEFINITIONS is simply the newer, more flexible and fine-grained way to do it.

They will always both be around: since 99%+ of the existing CMakeLists.txt files in the world use add_definitions, it simply would not be wise to remove it. The CMake devs work very hard to maintain backwards compatibility... sometimes to the detriment of clarity and simplicity. And sometimes doing essentially the same thing in multiple differing ways.

So: add_definitions is primarily useful to configure pre-existing CMakeLists files -- for those projects that have been around since before COMPILE_DEFINITIONS was introduced. And, since those projects use it, any newer projects that are based on what people learn from reading those CMakeLists files are also quite likely to use add_definitions.

But if using COMPILE_DEFINITIONS alone is sufficient for your needs, there's certainly nothing wrong with that.


I'm not say that something must be used.

It is just matter of your habit.

Some recommendations:

  • Use add_definitions when you want add to compiler command line for sources in the current directory and below. It is just shorter to type.

  • Use COMPILE_DEFINITIONS for fine tuning of target or specific sources.


If you want to add compile definition for target, you can use this function target_compile_definitions which is more convenient, like add multiple compile definitions once, like:

add_executable (trie_io_test demo12.cpp)
target_compile_definitions(trie_io_test PRIVATE UNIT_TESTING=1 IO_TEST=1)

You can see this question how to set multiple compile definitions for target executable for more information also from this https://cmake.org/cmake/help/v3.0/command/target_compile_definitions.html.

Tags:

C++

Cmake