TExcelTAD
Home › C/C++ Packages: Conan 2, vcpkg & CPM.cmake › Consuming Packages with conanfile.py

Consuming Packages with conanfile.py

conanfile.txt is a list. conanfile.py is a Python class, so it can make decisions: require a library only on one OS, pick a version from a file, pass values to CMake, and even drive the build. The same file format is used for consumers and for packages; a consumer just leaves out the name, version and packaging methods.

The same consumer in Python

python
from conan import ConanFile
from conan.tools.cmake import cmake_layout

class AppConan(ConanFile):
    settings = "os", "compiler", "build_type", "arch"
    generators = "CMakeDeps", "CMakeToolchain"

    def requirements(self):
        self.requires("spdlog/1.17.0")
        self.test_requires("catch2/3.16.0")

    def layout(self):
        cmake_layout(self)
  • settings declares which profile values the recipe reads. A consumer needs them so self.settings.os and friends exist.
  • requirements() replaces [requires]; self.test_requires() and self.tool_requires() (in build_requirements()) replace the other sections.
  • layout() replaces [layout].

Making decisions

Because it's Python, conditions are ordinary if statements. The generate() method replaces the generators attribute when you want to customise what's written; here it passes a CMake variable and the build type into the toolchain. A build() method lets conan build . run install, configure and build in one step:

bash · try it yourself
mkdir -p app && cd app
cat > conanfile.py <<'PY'
from conan import ConanFile
from conan.tools.cmake import CMake, CMakeDeps, CMakeToolchain, cmake_layout

class AppConan(ConanFile):
    settings = "os", "compiler", "build_type", "arch"
    options = {"with_logging": [True, False]}
    default_options = {"with_logging": True}

    def requirements(self):
        self.requires("fmt/12.1.0")
        if self.options.with_logging:
            self.requires("spdlog/1.17.0")
        if self.settings.os == "Windows":
            self.requires("wil/1.0.250325.1")   # never resolved on Linux

    def layout(self):
        cmake_layout(self)

    def generate(self):
        CMakeDeps(self).generate()
        tc = CMakeToolchain(self)
        tc.cache_variables["APP_WITH_LOGGING"] = bool(self.options.with_logging)
        tc.generate()

    def build(self):
        cmake = CMake(self)
        cmake.configure()
        cmake.build()
PY
cat > CMakeLists.txt <<'TXT'
cmake_minimum_required(VERSION 3.25)
project(app CXX)
option(APP_WITH_LOGGING "Log with spdlog" OFF)
find_package(fmt REQUIRED CONFIG)
add_executable(app main.cpp)
target_link_libraries(app PRIVATE fmt::fmt)
if(APP_WITH_LOGGING)
  find_package(spdlog REQUIRED CONFIG)
  target_link_libraries(app PRIVATE spdlog::spdlog)
  target_compile_definitions(app PRIVATE APP_WITH_LOGGING)
endif()
TXT
cat > main.cpp <<'SRC'
#include <fmt/core.h>
#ifdef APP_WITH_LOGGING
#include <spdlog/spdlog.h>
#endif
int main() {
#ifdef APP_WITH_LOGGING
    spdlog::set_pattern("[%l] %v");
    spdlog::info("logging enabled");
#endif
    fmt::print("answer = {}\n", 6 * 7);
}
SRC
conan build . -c tools.build:jobs=1 2>&1 | grep -E '^    [a-z]+/|RUN:|Built target'
./build/Release/app
echo "--- without logging"
conan build . -o "&:with_logging=False" -c tools.build:jobs=1 2>&1 | grep -E '^    [a-z]+/|Built target'
./build/Release/app
    fmt/12.1.0#6baf0fb8351783472b94ee6e36232391 - Cache
    spdlog/1.17.0#bcbaaf7147bda6ad24ffbd1ac3d7142c - Cache
    fmt/12.1.0#6baf0fb8351783472b94ee6e36232391:e02956bd268869d4519cb2b90dc7b4e51911a5d0#a857dc2fda2e0c13d61393798f6a9684 - Cache
    spdlog/1.17.0#bcbaaf7147bda6ad24ffbd1ac3d7142c:68cf2b888a31d527b3476ac5bf6707b2db1ccd2d#81ce70d6997cc1fbe7ed27c13c7c4bac - Cache
conanfile.py: RUN: cmake -G "Unix Makefiles" -DCMAKE_TOOLCHAIN_FILE="generators/conan_toolchain.cmake" -DCMAKE_INSTALL_PREFIX="/home/learner/app" -DAPP_WITH_LOGGING="ON" -DCMAKE_POLICY_DEFAULT_CMP0091="NEW" -DCMAKE_BUILD_TYPE="Release" "/home/learner/app"
conanfile.py: RUN: cmake --build "/home/learner/app/build/Release" -- -j1
[100%] Built target app
[info] logging enabled
answer = 42
--- without logging
    fmt/12.1.0#6baf0fb8351783472b94ee6e36232391 - Cache
    fmt/12.1.0#6baf0fb8351783472b94ee6e36232391:e02956bd268869d4519cb2b90dc7b4e51911a5d0#a857dc2fda2e0c13d61393798f6a9684 - Cache
[100%] Built target app
answer = 42

A few things to notice:

  • The Windows-only wil requirement never appears: on Linux that if is false, so Conan never even looks for the recipe.
  • &:with_logging=False sets an option of the consumer itself; & means "the root conanfile". (spdlog/*:shared=True would set a dependency's option.)
  • With logging off, spdlog disappears from the graph and CMake never calls find_package(spdlog).
  • conan build printed the exact cmake commands it ran (RUN:); you can always run them yourself instead.

conan build or conan install + CMake?

Both are fine. conan install + cmake --preset keeps CMake in charge and works naturally with IDEs (CLion and VS Code's CMake Tools pick up CMakeUserPresets.json). conan build is convenient in CI scripts and is the same code path conan create uses for packages, which you'll write in Creating a Package.

Useful attributes and methods for consumers

Member Use
settings which settings the recipe reads
options / default_options your own switches (consumers can have options too)
requirements() self.requires(ref), with keyword arguments such as override=True, force=True, visible=False
build_requirements() self.tool_requires("cmake/[>=3.25]"), self.test_requires(...)
configure() set dependencies' options: self.options["spdlog"].header_only = True
layout() folder layout, usually cmake_layout(self)
generate() customise generators (tc.cache_variables, tc.preprocessor_definitions)
build() the build commands used by conan build

Test yourself

What does -o "&:with_logging=False" mean?

  1. Set with_logging on every package
  2. Set the option on the root conanfile (the consumer itself)
  3. Disable all logging in Conan
  4. Set it on packages whose name starts with &

The conanfile requires wil inside if self.settings.os == "Windows". What happens on Linux?

  1. Conan downloads wil but doesn't link it
  2. The requirement is never added, so Conan never looks for wil
  3. An error, because wil isn't in the cache
  4. CMake skips it

Which method passes a value from the conanfile into CMake's cache?

  1. requirements()
  2. generate(), via CMakeToolchain's cache_variables
  3. layout()
  4. package_info()