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

ccmake

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?

Best Answer

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.

Related Topic