configure()

configure() 方法应用于配置食谱中的设置和选项,以供后续在不同方法(如 generate()build()package())中使用。此方法在构建依赖图并展开包依赖项时执行,这意味着当此方法执行时,依赖项尚未存在,因此无法访问 self.dependencies

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

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" 食谱属性(实验性),则上述 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") 将会移除 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 稳定性 部分。

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

auto_shared_fpic

自动管理的选项

  • fPIC (真, 假)。

  • shared (真, 假)。

  • header_only (真, 假)。

可以像这样添加到食谱中:

from conan import ConanFile

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

然后,如果食谱中未指定 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")

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

如果您需要在食谱中实现自定义行为,但同时也需要此逻辑,则必须明确声明。

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")

食谱可以为它们的依赖项选项建议值,例如 default_options = {"*:shared": True},但无法有条件地这样做。为此,也可以使用 configure() 方法。

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

注意

最佳实践

  • 请记住,在食谱中不可能定义 settingsconf 的值,它们是只读的。

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

另请参阅