Difference between define_property and set_property

Hello,

I am reading a CMake code with:

define_property(GLOBAL PROPERTY SomeLib_INCLUDED BRIEF_DOCS "Some doc" FULL_DOCS "Some full doc")
get_property(INCLUDED GLOBAL PROPERTY SomeLib_INCLUDED SET)

if(NOT INCLUDED)
  set_property(GLOBAL PROPERTY SomeLib_INCLUDED ON)
  ...
endif()

I don’t understand what is the purpose of define_property(). Why is it needed ?

Hi.

define_property() is not needed in this case. If you look at define_property() documentation, you will see that in modern CMake, it’s only really necessary to use it if you want the functionality offered by INHERITED and/or INITIALIZE_FROM_VARIABLE. For properties without these, define_property() is unnecessary, as a property get be get and set even without being defined.

At the same time, when a project uses a custom property, it’s a good idea to document the property and its use. This can be done using normal comment blocks, or the documentation arguments of define_property() can be used for it. In my code, I tend to stick to plain comments and only use define_property() when I need the inhertiance/initialisation behaviour, but I wouldn’t object to someone using define_property() for it.

But if define_property() is used, then get_property() always set the INCLUDED variable.
So we never go in the if() ?

I wasn’t able to reproduce this. When I copied the define_property() and get_property() commands from your post into a CMakeList, and then checked the INCLUDED variable, it was 0 (i.e. false).

Given the name of the property, is it possible that in your case, it’s set by a package/module you include?

No, it is set to ON in the if().
So, we won’t go in this if() the second time we’ll include the CMake file.

But I don’t understand why we go there the first time.

I’m confused. What first time/second time? Is this in a file included multiple times? Please bear in mind I can only reason from code you’ve shown, I know nothing about the code you haven’t shown.

If this is in a file (perhaps a package config or find module) that is included multiple times, then the first time it’s read, the property will not be set, so INCLUDED will be false and the if() will be entered. This causes the property to be set (to ON), so next time the get_property() is evaluated, it will set INCLUDED to true and so the if() will be skipped. I consider this expected behaviour; what would your expactation be? Note that define_property() has nothing to do with this, the code shown would behave 100% the same if that command was removed.

Your suppositions are good.

My initial question was due to the fact I thought define_property() defined and set SomeLib_INCLUDED. So get_property() shoudl have set INCLUDED.