configure()

configure() 方法应该用于在 recipe 中配置设置和选项,以便在generate()build()package()等不同方法中使用。此方法在构建依赖图并展开包依赖项时执行,这意味着当此方法执行时,依赖项仍然不存在,它们不存在,并且无法访问self.dependencies

例如,对于 C(非 C++)库,compiler.libcxxcompiler.cppstd 设置在build()期间甚至不应该存在。它们不仅不是package_id的一部分,而且根本不应该在构建过程中使用。它们将在 profile 中定义,因为图中的其他包可能是 C++ 包并且需要它们,但此 recipe 的责任是删除它们,以免在 recipe 中使用它们。

settings = "os", "compiler", "build_type", "arch"

def configure(self):
    # Not all compilers have libcxx subsetting, so we use rm_safe
    # to avoid exceptions
    self.settings.rm_safe("compiler.libcxx")
    self.settings.rm_safe("compiler.cppstd")

def package_id(self):
    # No need to delete those settings here, they were already deleted
    pass

注意

从 Conan 2.4 开始,如果定义了languages = "C" recipe 属性(实验性的),则不需要上述configure()

对于您想移除设置的所有子集设置的包,您可以使用rm_safe方法并带有一个通配符。

settings = "os", "compiler", "build_type", "arch"

def configure(self):
    self.settings.rm_safe("compiler.*")

这将移除compiler设置的所有子设置,例如compiler.libcxxcompiler.cppstd,但会保留compiler设置本身(self.settings.rm_safe("compiler")会移除它)。

同样,对于包含库的包,fPIC选项实际上只在库被编译为静态库时适用,但否则,fPIC选项没有意义,所以应该移除它。

options = {"shared": [True, False], "fPIC": [True, False]}
default_options = {"shared": False, "fPIC": True}

def configure(self):
    if self.options.shared:
        # fPIC might have been removed in config_options(), so we use rm_safe
        self.options.rm_safe("fPIC")

可用的自动实现

警告

此功能是实验性的,可能会发生重大更改。有关更多信息,请参阅 Conan 稳定性 部分。

当 recipe 中未定义configure()方法时,Conan 可以自动管理一些在implements ConanFile 属性中指定的约定选项。

auto_shared_fpic

自动管理选项

  • fPIC (True, False)。

  • shared (True, False)。

  • header_only (True, False)。

它可以这样添加到 recipe 中:

from conan import ConanFile

class Pkg(ConanFile):
    implements = ["auto_shared_fpic"]
    ...

然后,如果在 recipe 中未指定configure()方法,Conan 将在configure步骤中自动管理 fPIC 设置,如下所示:

if conanfile.options.get_safe("header_only"):
    conanfile.options.rm_safe("fPIC")
    conanfile.options.rm_safe("shared")
elif conanfile.options.get_safe("shared"):
    conanfile.options.rm_safe("fPIC")

请注意,将此实现添加到 recipe 中也可能会影响configure步骤。

如果您需要在 recipe 中实现自定义行为,但同时需要此逻辑,则必须显式声明。

def configure(self):
    if conanfile.options.get_safe("header_only"):
        conanfile.options.rm_safe("fPIC")
        conanfile.options.rm_safe("shared")
    elif conanfile.options.get_safe("shared"):
        conanfile.options.rm_safe("fPIC")
    self.settings.rm_safe("compiler.libcxx")
    self.settings.rm_safe("compiler.cppstd")

Recipe 可以为其依赖项选项建议值,如default_options = {"*:shared": True},但无法有条件地进行。为此,也可以使用configure()方法。

def configure(self):
    if something:
        self.options["*"].shared = True

注意

最佳实践

  • 请记住,在 recipe 中**无法**定义settingsconf值,它们是只读的。

  • options值的定义仅仅是一个“建议”,根据图的计算、优先级等,options的最终值可能与 recipe 设置的值不同。

另请参阅