tool_requires中透明地使用cmake模块

当我们需要重用另一个Conan包中的一些.cmake脚本时,有几种不同的可能场景,例如.cmake脚本位于常规的requirestool_requires中。

此外,可能有两种不同的方法

  • 脚本的消费者可以在其CMakeLists.txt中显式地执行include(MyScript)。这种方法非常明确且设置更简单,只需在配方中定义self.cpp_info.builddirs,并且使用CMakeToolchain的消费者将能够自动执行include()并使用该功能。请参阅此处的示例

  • 消费者希望在执行find_package()时自动加载依赖的cmake模块。本示例实现了这种情况。

假设我们有一个包,打算用作tool_require,其配方如下

myfunctions/conanfile.py
import os
from conan import ConanFile
from conan.tools.files import copy

class Conan(ConanFile):
    name = "myfunctions"
    version = "1.0"
    exports_sources = ["*.cmake"]

    def package(self):
        copy(self, "*.cmake", self.source_folder, self.package_folder)

    def package_info(self):
        self.cpp_info.set_property("cmake_build_modules", ["myfunction.cmake"])

以及一个myfunction.cmake文件,位于

myfunctions/myfunction.cmake
function(myfunction)
    message("Hello myfunction!!!!")
endfunction()

我们可以执行cd myfunctions && conan create .,这将创建包含cmake脚本的myfunctions/1.0包。

然后,消费者包将如下所示

consumer/conanfile.py
from conan import ConanFile
from conan.tools.cmake import CMake, CMakeDeps, CMakeToolchain

class Conan(ConanFile):
    settings = "os", "compiler", "build_type", "arch"
    tool_requires = "myfunctions/1.0"

    def generate(self):
        tc = CMakeToolchain(self)
        tc.generate()

        deps = CMakeDeps(self)
        # By default 'myfunctions-config.cmake' is not created for tool_requires
        # we need to explicitly activate it
        deps.build_context_activated = ["myfunctions"]
        # and we need to tell to automatically load 'myfunctions' modules
        deps.build_context_build_modules = ["myfunctions"]
        deps.generate()

    def build(self):
        cmake = CMake(self)
        cmake.configure()

以及一个CMakeLists.txt文件,如下所示

consumer/CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(test)
find_package(myfunctions CONFIG REQUIRED)
myfunction()

然后,消费者将能够自动调用依赖模块中的myfunction()

$ conan build .
...
Hello myfunction!!!!

如果由于某种原因,消费者希望强制将tool_requires()用作CMake模块,消费者可以执行deps.set_property("myfunctions", "cmake_find_mode", "module", build_context=True),然后find_package(myfunctions MODULE REQUIRED)将生效。