Search code examples
c++cmakeconan

Can I make conan usage optional to users of my library that uses conan?


Using conan to develop a library seems to force users of the library to also use conan. Is there a (standard) way I can replace the CONAN_PKG::protobuf reference in Targets.cmake with just protobuf?

Context

I am using cmake to build a static C++ library using protobuf, using conan to handle the protobuf dependency, ie

target_link_libraries(mylib
    PUBLIC
        CONAN_PKG::protobuf
    )

When I install this library locally , ie ninja install the created MylibTargets.cmake contains a reference to CONAN_PKG::protobuf

set_target_properties(Mylib::Mylib PROPERTIES
  INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include/mylib;${_IMPORT_PREFIX}/include"
  INTERFACE_LINK_LIBRARIES "CONAN_PKG::protobuf"

This forces users of my library to use conan to resolve the CONAN_PKG::protobuf dependency. (I want users of the library to be able to use the protobuf headerfiles).

I am using

install(EXPORT MylibTargets
    FILE MylibTargets.cmake
    NAMESPACE Mylib::
    DESTINATION lib/cmake/mylib
    )

to generate MylibTargest.cmake


Solution

  • Yes, all the modern CMake integrations can achieve some level of transparent integration. First attempts are cmake_find_package and cmake_find_package_multi, but the most modern one are:

    • CMakeDeps: see docs generates xxx-config.cmake scripts, so consumers can do a normal find_package(protobuf ...)
    • CMakeToolchain: see docs generates a conan_toolchain.cmake to help mapping the Conan settings to CMake syntax (and can be used with -DCMAKE_TOOLCHAIN_FILE=conan_toolchain.cmake

    With this integration, it is possible to keep CMakeLists.txt completely agnostic of Conan. This integration will become the standard one in Conan 2.0.