I'm having trouble understanding when to use target_compile_definitions(...)
vs set(COMPILE_DEFINITIONS ...)
. Is the difference that target_compile_definitions
will only affect a specific target?
-
Possible duplicate of [Is Cmake set variable recursive?](https://stackoverflow.com/questions/33828855/is-cmake-set-variable-recursive) – Florian Dec 01 '17 at 07:56
-
Do you mean `add_definitions(...)` instead of `set(COMPILE_DEFINITIONS ...)`? If so, yes, `add_definitions` affects on all targets in the current scope, but `target_compile_definitions` affects only on specific target. – Tsyvarev Dec 01 '17 at 07:57
-
@Tsyvarev Maybe I could have worded my questions better, but I was actually interested in the difference between setting variables directly using set() versus through commands. So maybe a better question was what is the difference between doing set(COMPILE_DEFINITIONS) and add_definitions? – Dec 01 '17 at 13:41
-
Variable *COMPILE_DEFINITIONS* has **no special meaning** for CMake (variables with special meaning are listed in [documentation](https://cmake.org/cmake/help/v3.10/manual/cmake-variables.7.html)). So setting this variable doesn't add any compile definition. Unless you *explicitely* use this variable somewhere else. – Tsyvarev Dec 01 '17 at 14:03
1 Answers
One thing to realize is that set(COMPILE_DEFINITIONS ...)
does not alter any target in any way.
What does it mean? Well, you just create a new variable (called COMPILE_OPTIONS
), which will be cached after the first configuration run. That's all. Nothing else happens.
Now, next thing to realize is that there exist properties, and that is what you meant. Properties are some different "context", "payload" for targets, directories, source files, etc. Documentation says that there are:
- Properties of Global Scope
- Properties on Directories
- Properties on Targets
- Properties on Tests
- Properties on Source Files
- Properties on Cache Entries
- Properties on Installed Files
Documentation also says that COMPILE_DEFINITIONS
is a property that exists for both directory scope and target scope. It means that every directory that you have and every target you've declared has this property, and the property value can be different for each of them. One uses set_property()
to set a property for the needed scope.
Now, what is target_compile_definitions()
? That's just the equivalent of set_property(TARGET ... PROPERTY COMPILE_DEFINITIONS ...)
.
So, in essence, all these target_
functions are just doing that, but have a distinct function for it. However, CMake doesn't have a function for every property, so here's again some inconsistency to deal with.
But, just remember that what set()
does and what a property is are two orthogonal things.