1. 程式人生 > >cmake:用於查詢libjpeg-turbo的module FindTurboJPEG.cmake

cmake:用於查詢libjpeg-turbo的module FindTurboJPEG.cmake

libjpeg-turbo的安裝包沒有提供用於CONFIG模式查詢包(find_package)的cmake指令碼,如果cmake指令碼中要查詢libjpeg-turbo庫,就得自己寫指令碼。
於是我參照cmake 查詢標準libjpeg庫 的Module FindJPEG原始碼的寫法實現了libjpeg-turbo的Module FindTurboJPEG.cmake。
為了更方便引用libjpeg-turbo,module中不僅提供了傳統的變數方式TURBOJPEG_INCLUDE_DIRTURBOJPEG_LIBRARY提供libjpeg-turbo的資訊,還提供import target:turbojpep

,turbojpeg-static

# 通過查詢turbojpeg.h定位libjpeg-turbo的include資料夾位置
find_path(TURBOJPEG_INCLUDE_DIR turbojpeg.h)

set(TURBOJPEG_NAMES ${TURBOJPEG_NAMES} turbojpeg libturbojpeg)
find_library(TURBOJPEG_LIBRARY NAMES ${TURBOJPEG_NAMES} )

# handle the QUIETLY and REQUIRED arguments and set TURBOJPEG_FOUND to TRUE if
# all listed variables are TRUE include(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(TURBOJPEG DEFAULT_MSG TURBOJPEG_LIBRARY TURBOJPEG_INCLUDE_DIR) if(TURBOJPEG_FOUND) # for compatility of find_dependency set (TurboJPEG_FOUND TRUE) # Create imported target turbojpeg
add_library(turbojpep SHARED IMPORTED) # import target中指定include資料夾 set_target_properties(turbojpep PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES "C" INTERFACE_INCLUDE_DIRECTORIES "${TURBOJPEG_INCLUDE_DIR}" IMPORTED_LOCATION "${TURBOJPEG_LIBRARY}" ) if(MSVC) set(_stati_library_name ${CMAKE_STATIC_LIBRARY_PREFIX}turbojpeg-static${CMAKE_STATIC_LIBRARY_SUFFIX}) else() set(_stati_library_name ${CMAKE_STATIC_LIBRARY_PREFIX}turbojpeg${CMAKE_STATIC_LIBRARY_SUFFIX}) endif() # 查詢libjpeg-turbo靜態庫 find_library(TURBOJPEG_LIBRARY_STATIC ${_stati_library_name}) # 如果找到靜態庫,則建立turbojpeg-static target if(TURBOJPEG_LIBRARY_STATIC) # Create imported target turbojpeg-static add_library(turbojpeg-static STATIC IMPORTED) # import target中指定include資料夾 set_target_properties(turbojpeg-static PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES "C" INTERFACE_INCLUDE_DIRECTORIES "${TURBOJPEG_INCLUDE_DIR}" IMPORTED_LOCATION "${TURBOJPEG_LIBRARY_STATIC}" ) message(STATUS "TURBOJPEG_LIBRARY_STATIC=${TURBOJPEG_LIBRARY_STATIC}") else() message(STATUS "NOT FOUND jpeg-turbo static library") endif() unset(_stati_library_name) endif() mark_as_advanced(TURBOJPEG_LIBRARY TURBOJPEG_INCLUDE_DIR )

import target引用示例:

# 需要將FindTurboJPEG.cmake的位置加入CMAKE_PREFIX_PATH,cmake才能找到
find_package(TurboJPEG REQUIRED)
## 優先使用靜態庫
if(TARGET turbojpeg-static)
    set (_turbojpeg_target "turbojpeg-static")
else()
    set (_turbojpeg_target "turbojpeg")
endif()
# 因為import target已經包含了libjpeg-turbo的include資訊,
# 所以會自動傳遞被引入的專案mytarget,所以mytarget 不必再單獨新增include_directories
target_link_libraries(mytarget ${_turbojpeg_target})