TExcelTAD
Home › C/C++ Packages: Conan 2, vcpkg & CPM.cmake › Recipe Methods: layout to package_info

Recipe Methods: layout to package_info

A recipe is a class whose methods Conan calls at specific moments. Knowing when each runs, and in which folder, is what makes recipes easy to write and debug. This lesson writes a recipe by hand, for a library that itself depends on fmt.

The methods, in order

Method Runs Typical job
set_name(), set_version() on export compute name/version (from Git, a file)
export(), export_sources() on export copy extra files into the cache
config_options(), configure() while building the graph remove or adjust options; set dependencies' options
layout() everywhere define source, build and generators folders
requirements(), build_requirements() while building the graph declare dependencies
validate() after the graph raise ConanInvalidConfiguration for unsupported setups
package_id(), compatibility() computing binaries adjust the package ID, offer fallbacks
source() once per recipe revision download/patch the source (get(), git.clone())
generate() before building write toolchain and dependency files
build() building run the build system
package() after build copy artifacts into the package folder
package_info() when consumed describe the package to consumers (cpp_info)
test() in test_package only run something to prove the package works

Methods are optional: a recipe without source() uses its exports_sources; a header-only library has no build().

A hand-written recipe

The library textfmt formats tables with fmt. Its public header includes fmt, so consumers need fmt's headers too: that's transitive_headers=True. package_info() also chooses the CMake names consumers will use:

bash · try it yourself
mkdir -p textfmt/src textfmt/include/textfmt && cd textfmt
cat > conanfile.py <<'PY'
from conan import ConanFile
from conan.errors import ConanInvalidConfiguration
from conan.tools.build import check_min_cppstd
from conan.tools.cmake import CMake, CMakeDeps, CMakeToolchain, cmake_layout

class TextFmtRecipe(ConanFile):
    name = "textfmt"
    version = "0.3.0"
    license = "MIT"
    package_type = "static-library"
    settings = "os", "arch", "compiler", "build_type"
    options = {"fPIC": [True, False]}
    default_options = {"fPIC": True}
    exports_sources = "CMakeLists.txt", "src/*", "include/*"

    def requirements(self):
        self.requires("fmt/[>=12.0 <13]", transitive_headers=True)

    def validate(self):
        check_min_cppstd(self, 17)
        if self.settings.os == "Windows":
            raise ConanInvalidConfiguration("textfmt hasn't been ported to Windows yet")

    def layout(self):
        cmake_layout(self)

    def generate(self):
        CMakeDeps(self).generate()
        CMakeToolchain(self).generate()

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

    def package(self):
        CMake(self).install()

    def package_info(self):
        self.cpp_info.libs = ["textfmt"]
        self.cpp_info.set_property("cmake_file_name", "TextFmt")
        self.cpp_info.set_property("cmake_target_name", "TextFmt::textfmt")
PY
cat > CMakeLists.txt <<'TXT'
cmake_minimum_required(VERSION 3.25)
project(textfmt CXX)
find_package(fmt REQUIRED CONFIG)
add_library(textfmt src/table.cpp)
target_include_directories(textfmt PUBLIC include)
target_link_libraries(textfmt PUBLIC fmt::fmt)
install(TARGETS textfmt)
install(DIRECTORY include/ DESTINATION include)
TXT
cat > include/textfmt/table.h <<'SRC'
#pragma once
#include <fmt/format.h>
#include <string>
#include <utility>
#include <vector>
namespace textfmt {
std::string table(const std::vector<std::pair<std::string, int>>& rows);
}
SRC
cat > src/table.cpp <<'SRC'
#include "textfmt/table.h"
std::string textfmt::table(const std::vector<std::pair<std::string, int>>& rows) {
    std::string out = fmt::format("+{:-<10}+{:->6}+\n", "", "");
    for (auto& [k, v] : rows) out += fmt::format("|{:<10}|{:>6}|\n", k, v);
    return out + fmt::format("+{:-<10}+{:->6}+\n", "", "");
}
SRC
conan create . -c tools.build:jobs=1 --test-folder="" 2>&1 | grep -E 'Resolved|fmt/\[|: Package |ERROR'
echo "--- on Windows:"
conan graph info . -s os=Windows -s compiler=msvc -s compiler.version=194 -s compiler.runtime=dynamic -s compiler.cppstd=17 -nr 2>&1 | grep -E 'Invalid|textfmt hasn'
Resolved version ranges
    fmt/[>=12.0 <13]: fmt/12.1.0
textfmt/0.3.0: Package 'c507211a910a97d6e61482662aefc83cf4854d8d' built
--- on Windows:
  info_invalid: textfmt hasn't been ported to Windows yet
  • --test-folder="" skips the test step (this recipe has no test_package/ yet; the next lesson adds one).
  • validate() didn't stop the graph for Windows, it marked the binary invalid: conan graph info reports it, and conan install would fail with that message instead of attempting a build that can't work.

package_info() in detail

package_info() is the contract with consumers, and CMakeDeps reads it:

python
def package_info(self):
    # names used by CMakeDeps: find_package(TextFmt) and target TextFmt::textfmt
    self.cpp_info.set_property("cmake_file_name", "TextFmt")
    self.cpp_info.set_property("cmake_target_name", "TextFmt::textfmt")
    self.cpp_info.set_property("pkg_config_name", "textfmt")   # for PkgConfigDeps
    self.cpp_info.libs = ["textfmt"]
    self.cpp_info.defines = ["TEXTFMT_STATIC"]
    if self.settings.os == "Linux":
        self.cpp_info.system_libs = ["m", "pthread"]

    # or: several components, each its own CMake target
    # self.cpp_info.components["core"].libs = ["textfmt_core"]
    # self.cpp_info.components["core"].requires = ["fmt::fmt"]
    # self.cpp_info.components["cli"].requires = ["core"]

The defaults (includedirs=["include"], libdirs=["lib"], bindirs=["bin"]) match a standard cmake --install layout, which is why package() is usually just cmake.install().

Recipes for third-party code

When the source isn't yours, a recipe downloads it in source() and pins it with a checksum, usually through conandata.yml:

yaml
# conandata.yml
sources:
  "1.4.2":
    url: "https://example.com/releases/libfoo-1.4.2.tar.gz"
    sha256: "<sha256 of the archive>"
python
from conan.tools.files import get

def source(self):
    get(self, **self.conan_data["sources"][self.version], strip_root=True)

That's the pattern every ConanCenter recipe follows (you saw fmt's get(...) line in the Settings vs Options error). The source is downloaded once per recipe revision and kept in the cache's source folder.

Test yourself

Which method should reject configurations a library doesn't support?

  1. configure()
  2. validate(), raising ConanInvalidConfiguration
  3. build()
  4. package_info()

textfmt's public header includes <fmt/format.h>. What does the recipe need?

  1. Nothing
  2. transitive_headers=True on the fmt requirement
  3. fmt as a tool_requires
  4. A copy of fmt's headers

How do you make CMakeDeps generate find_package(TextFmt) with target TextFmt::textfmt?

  1. Rename the recipe
  2. set_property("cmake_file_name", ...) and set_property("cmake_target_name", ...) in package_info()
  3. Edit the generated files
  4. Use a CMake alias in the consumer