In CMake documentation, we can read:
add_definitions
Adds flags to the compiler command line for sources in the current directory and below.
COMPILE_DEFINITIONS property on directories
COMPILE_DEFINITIONS: Preprocessor definitions for compiling a directory's sources.
COMPILE_DEFINITIONS property on targets
COMPILE_DEFINITIONS: Preprocessor definitions for compiling a target's sources.
COMPILE_DEFINITIONS property on source files
COMPILE_DEFINITIONS: Preprocessor definitions for compiling a source file.
COMPILE_DEFINITIONS
and add_definitions
functionality seems to overlap. COMPILE_DEFINITIONS
property seems more flexible.
So it seems that COMPILE_DEFINITIONS property does everything add_definitions does, and even more.
So, in which cases must we call add_definitions because COMPILE_DEFINITIONS property cannot be used?
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 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 tunning 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.