[CMake] Using find_package() portably?

Johannes Zarl-Zierl johannes.zarl-zierl at jku.at
Wed Nov 29 06:02:01 EST 2017


Hello Carsten,

On Samstag, 25. November 2017 11:46:44 CET Carsten Fuchs wrote:
> Thanks for your reply, but how can I proceed from here?
> 
> In order to be able to write in the parent script something that works
> in either case, that is,
> 
> target_link_libraries(main_program <either JPEG::JPEG or ${JPEG...} or ???>)

Well, that's one way, but that doesn't really provide any benefit above the 
original solution (i.e. just define the JPEG_INCLUDES and JPEG_LIBRARIES 
variables accordingly).

> it seems that I either
> 
>    - have to make a copy of FindJPEG.cmake, customize it to define
> target JPEG::JEPG and ship it along with my project,

Either that or you define it yourself:
find_package(JPEG)
if (JPEG_FOUND)
 add_library(JPEG::JPEG UNKNOWN IMPORTED)
 set_property(
  TARGET JPEG::JPEG
  PROPERTY IMPORTED_LOCATION ${JPEG_LIBRARIES}
  )
 set_property(
  TARGET JPEG::JPEG PROPERTY
  INTERFACE_INCLUDE_DIRECTORIES ${JPEG_INCLUDES}
 )
endif()

I admit it's not a huge benefit over just using the variables. The advantages:
- you get slightly better error handling
- your target_link_libraries commands are slightly more readable.

>    - or write my `../ExtLibs/libjpeg/CMakeLists.txt` so that it globally
> defines JPEG_LIBRARIES and JPEG_INCLUDE_DIRS

That will work, too.


Cheers,
  Johannes



More information about the CMake mailing list