Search code examples
cmakelibraw

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


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.


Solution

  • 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...