Wednesday, December 02, 2020

CMake: Use new style imported targets to link libraries

 What does that mean?


It means this https://invent.kde.org/graphics/okular/-/commit/3129b642f996589f1c7fcee513741e1993924241


That is, you add JPEG::JPEG to target_link_libraries, and that's it, no need to add the includes, the compile_definitions and whatnot.

 

This has multiple advantages to the old mode:

  • You can't misspell it, since these are actual things cmake knows about not strings so if you write something like JPEG::JPG it will fail at cmake stage
  • You won't forget to add the include (most of us did at some point) because you don't need to :)
  • The include path is just for that particular target (the old method added it to "everyone")
  • It's basically less lines so it's harder to do wrong

 

To know if you can use that you'll need to use the cmake help, for example the imported target is described at https://cmake.org/cmake/help/latest/module/FindJPEG.html


Now we don't probably depend on cmake 3.19, do we? So we need to make sure the cmake we say we support has that, so use the combo on the top of that page to go and find which version introduced it, for JPEG we can see it was cmake 3.12

2 comments:

Anonymous said...

Hi,
Is there a reason not using new style imports for ZLIB (https://cmake.org/cmake/help/latest/module/FindZLIB.html)?

Albert Astals Cid said...

No reason, no.

https://invent.kde.org/graphics/okular/-/commit/3cc7bdd1d78c31f86e5b4e437fa60f66a5044e2d

The reason you don't see it in the linked commit is that commits should be ideally as small and atomic as possible.