添加软件包依赖项

之前的教程章节中,我们为 “Hello World” C++ 库创建了一个 Conan 软件包。我们使用了 conan.tools.scm.Git() 工具从 git 仓库检索源文件。到目前为止,该软件包没有任何对其他 Conan 软件包的依赖。让我们解释一下如何像在 使用软件包章节中所做的那样,以非常相似的方式向我们的软件包添加依赖项。我们将使用 fmt 库为我们的 “Hello World” 库添加一些花哨的颜色输出。

请首先克隆源文件以重新创建此项目。您可以在 GitHub 上的 examples2 仓库中找到它们

$ git clone https://github.com/conan-io/examples2.git
$ cd examples2/tutorial/creating_packages/add_requires

您会注意到之前 recipe 中的 conanfile.py 文件发生了一些更改。让我们检查一下相关的部分

...
from conan.tools.build import check_max_cppstd, check_min_cppstd
...

class helloRecipe(ConanFile):
    name = "hello"
    version = "1.0"

    ...
    generators = "CMakeDeps"
    ...

    def validate(self):
        check_min_cppstd(self, "11")
        check_max_cppstd(self, "20")

    def requirements(self):
        self.requires("fmt/8.1.1")

    def source(self):
        git = Git(self)
        git.clone(url="https://github.com/conan-io/libhello.git", target=".")
        # Please, be aware that using the head of the branch instead of an immutable tag
        # or commit is not a good practice in general
        git.checkout("require_fmt")
  • 首先,我们设置了 generators 类属性,使 Conan 调用 CMakeDeps 生成器。这在之前的 recipe 中是不需要的,因为我们没有依赖项。CMakeDeps 将生成 CMake 查找 fmt 库所需的所有配置文件。

  • 接下来,我们使用 requires() 方法将 fmt 依赖项添加到我们的软件包中。

  • 此外,请检查我们在 source() 方法中添加了额外的行。我们使用 Git().checkout 方法检出 require_fmt 分支中的源代码。此分支包含源代码中的更改,以向库消息添加颜色,以及在 CMakeLists.txt 中声明我们正在使用 fmt 库。

  • 最后,请注意我们向 recipe 添加了 validate() 方法。我们已经在 使用软件包章节 中使用过此方法,以便为不支持的配置引发错误。在这里,我们调用 check_min_cppstd()check_max_cppstd() 来检查我们在设置中至少使用 C++11 且至多使用 C++20 标准。

您可以查看新源文件,在 require_fmt 中使用 fmt 库。您将看到 hello.cpp 文件向输出消息添加了颜色

#include <fmt/color.h>

#include "hello.h"

void hello(){
    #ifdef NDEBUG
    fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold, "hello/1.0: Hello World Release!\n");
    #else
    fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold, "hello/1.0: Hello World Debug!\n");
    #endif
    ...

让我们使用当前默认配置从源文件构建软件包,然后让 test_package 文件夹测试该软件包。您现在应该看到带有颜色的输出消息

$ conan create . --build=missing
-------- Exporting the recipe ----------
...
-------- Testing the package: Running test() ----------
hello/1.0 (test package): Running test()
hello/1.0 (test package): RUN: ./example
hello/1.0: Hello World Release!
  hello/1.0: __x86_64__ defined
  hello/1.0: __cplusplus 201103
  hello/1.0: __GNUC__ 4
  hello/1.0: __GNUC_MINOR__ 2
  hello/1.0: __clang_major__ 13
  hello/1.0: __clang_minor__ 1
  hello/1.0: __apple_build_version__ 13160021