[CMake] Using find_package() portably?

Johannes Zarl-Zierl johannes.zarl-zierl at jku.at
Wed Nov 22 06:03:45 EST 2017


On Mittwoch, 22. November 2017 11:32:22 CET Carsten Fuchs wrote:
> That is, follow-up question: near the "..." above, we have got a target
> "libjpeg", but how do I get the variables JPEG_INCLUDES, JPEG_LIBRARIES
> etc. that `find_package(JPEG)` normally provides so that the last line
> with the `target_link_libraries()` works?
> I guess that defining them in `../ExtLibs/libjpeg/CMakeLists.txt` is wrong.

You've found an ugly corner in CMake ;-)

The problem in this specific case is that CMake ships with a FindJPEG module 
that does not define modern import libs, but uses the old way of defining 
<PACKAGE>_LIBRARIES and <PACKAGE>_INCLUDE_DIRS.
IMO this highlights one of the main problems with find modules: nobody really 
maintains them.

If JPEG had proper imported targets, your code could look like this:

find_package(JPEG)   # without "REQUIRED"

if (NOT JPEG_FOUND)
   ...
   # Proceed with the shipped copy of libjpeg:
   add_subdirectory(../ExtLibs/libjpeg ../ExtLibs/libjpeg)
endif()

target_link_libraries(main_program JPEG::JPEG)

You just have to make sure that your shipped libjpeg creates the proper 
namespaced target:
add_library(JPEG ...)
add_library(JPEG::JPEG ALIAS JPEG)

HTH,
  Johannes



More information about the CMake mailing list