How to wrap external paths (include, lib) and definitions into a target in cmake

216 Views Asked by At

Rather than providing a target, some libraries like LibRaw generate variables that contain information about include paths, library paths and compile definitions. In the case of LibRaw, vcpkg recommends the following usage:

target_compile_definitions(main PRIVATE ${LibRaw_DEFINITIONS})
target_include_directories(main PRIVATE ${LibRaw_INCLUDE_DIR})
target_link_libraries(main PRIVATE ${LibRaw_LIBRARIES})

However, I would much rather stay consistent on linking libraries using

target_link_libraries(main PRIVATE LibRaw)

Is there a way to wrap all of the provided variables into a target.

2

There are 2 best solutions below

0
On BEST ANSWER

You should be able to create your own interface library and define the properties that should be applied to the main target with INTERFACE visibility:

add_library(MyLibRaw INTERFACE)
target_compile_definitions(MyLibRaw INTERFACE ${LibRaw_DEFINITIONS})
target_include_directories(MyLibRaw INTERFACE ${LibRaw_INCLUDE_DIR})
target_link_libraries(MyLibRaw INTERFACE ${LibRaw_LIBRARIES})

This way every linking target linking MyLibRaw will inherit those properties.

target_link_libraries(main PRIVATE MyLibRaw)

Note that if you're reusing the target across multiple projects, you may want to create a find script that provides this target, if you do find_package(MyImports COMPONENTS LibRaw) or similar...

0
On

You can create your own target:

add_library( MyLibRaw INTERFACE IMPORTED )

set_target_properties(MyLibRaw 
    PROPERTIES
        INTERFACE_INCLUDE_DIRECTORIES ${LibRaw_INCLUDE_DIR}
        IMPORTED_IMPLIB_DEBUG ${LibRaw_LIBRARIES_debug}
        IMPORTED_IMPLIB_RELEASE ${LibRaw_LIBRARIES_release}
        IMPORTED_LOCATION_DEBUG ${LibRaw_LIBRARIES_shared_debug}
        IMPORTED_LOCATION_RELEASE ${LibRaw_LIBRARIES_shared_release}
)

target_link_libraries(MyLibRaw 
    INTERFACE
        optimized $<TARGET_PROPERTY:MyLibRaw ,IMPORTED_IMPLIB_RELEASE>
        debug $<TARGET_PROPERTY:MyLibRaw ,IMPORTED_IMPLIB_DEBUG>
)