Build packages: the build() method

We already used a Conan recipe that has a build() method and learned how to use that to invoke a build system and build our packages. In this tutorial, we will modify that method and explain how you can use it to do things like:

  • Building and running tests

  • Conditional patching of the source code

  • Select the build system you want to use conditionally

Please, first clone the sources to recreate this project. You can find them in the examples2 repository on GitHub:

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

Build and run tests for your project

You will notice some changes in the conanfile.py file from the previous recipe. Let’s check the relevant parts:

Changes introduced in the recipe

conanfile.py

  1. class helloRecipe(ConanFile):
  2. name = "hello"
  3. version = "1.0"
  4. ...
  5. def source(self):
  6. git = Git(self)
  7. git.clone(url="https://github.com/conan-io/libhello.git", target=".")
  8. # Please, be aware that using the head of the branch instead of an immutable tag
  9. # or commit is not a good practice in general
  10. git.checkout("with_tests")
  11. ...
  12. def requirements(self):
  13. if self.options.with_fmt:
  14. self.requires("fmt/8.1.1")
  15. self.test_requires("gtest/1.11.0")
  16. ...
  17. def generate(self):
  18. tc = CMakeToolchain(self)
  19. if self.options.with_fmt:
  20. tc.variables["WITH_FMT"] = True
  21. tc.generate()
  22. def build(self):
  23. cmake = CMake(self)
  24. cmake.configure()
  25. cmake.build()
  26. if not self.conf.get("tools.build:skip_test", default=False):
  27. test_folder = os.path.join("tests")
  28. if self.settings.os == "Windows":
  29. test_folder = os.path.join("tests", str(self.settings.build_type))
  30. self.run(os.path.join(test_folder, "test_hello"))
  31. ...
  • We added the gtest/1.11.0 requirement to the recipe as a test_requires(). It’s a type of requirement intended for testing libraries like Catch2 or gtest.

  • We use the tools.build:skip_test configuration (False by default), to tell CMake whether to build and run the tests or not. A couple of things to bear in mind:

    • If we set the tools.build:skip_test configuration to True Conan will automatically inject the BUILD_TESTING variable to CMake set to OFF. You will see in the next section that we are using this variable in our CMakeLists.txt to decide whether to build the tests or not.

    • We use the tools.build:skip_test configuration in the build() method, after building the package and tests, to decide if we want to run the tests or not.

    • In this case we are using gtest for testing and we have to check if the build method is to run the tests or not. This configuration also affects the execution of CMake.test() if you are using CTest and Meson.test() for Meson.

Changes introduced in the library sources

First, please note that we are using another branch from the libhello library. This branch has two novelties on the library side:

  • We added a new function called compose_message() to the library sources so we can add some unit tests over this function. This function is just creating an output message based on the arguments passed.

  • As we mentioned in the previous section the CMakeLists.txt for the library uses the BUILD_TESTING CMake variable that conditionally adds the tests directory.

CMakeLists.txt

  1. cmake_minimum_required(VERSION 3.15)
  2. project(hello CXX)
  3. ...
  4. if (NOT BUILD_TESTING STREQUAL OFF)
  5. add_subdirectory(tests)
  6. endif()
  7. ...

The BUILD_TESTING CMake variable is declared and set to OFF by Conan (if not already defined) whenever the tools.build:skip_test configuration is set to value True. This variable is typically declared by CMake when you use CTest but using the tools.build:skip_test configuration you can use it in your CMakeLists.txt even if you are using another testing framework.

tests/CMakeLists.txt

  1. cmake_minimum_required(VERSION 3.15)
  2. project(PackageTest CXX)
  3. find_package(GTest REQUIRED CONFIG)
  4. add_executable(test_hello test.cpp)
  5. target_link_libraries(test_hello GTest::gtest GTest::gtest_main hello)

With basic tests on the functionality of the compose_message() function:

tests/test.cpp

  1. #include "../include/hello.h"
  2. #include "gtest/gtest.h"
  3. namespace {
  4. TEST(HelloTest, ComposeMessages) {
  5. EXPECT_EQ(std::string("hello/1.0: Hello World Release! (with color!)\n"), compose_message("Release", "with color!"));
  6. ...
  7. }
  8. }

Now that we have gone through all the changes in the code, let’s try them out:

  1. $ conan create . --build=missing -tf=""
  2. ...
  3. [ 25%] Building CXX object CMakeFiles/hello.dir/src/hello.cpp.o
  4. [ 50%] Linking CXX static library libhello.a
  5. [ 50%] Built target hello
  6. [ 75%] Building CXX object tests/CMakeFiles/test_hello.dir/test.cpp.o
  7. [100%] Linking CXX executable test_hello
  8. [100%] Built target test_hello
  9. hello/1.0: RUN: ./tests/test_hello
  10. Capturing current environment in /Users/user/.conan2/p/tmp/c51d80ef47661865/b/build/generators/deactivate_conanbuildenv-release-x86_64.sh
  11. Configuring environment variables
  12. Running main() from /Users/user/.conan2/p/tmp/3ad4c6873a47059c/b/googletest/src/gtest_main.cc
  13. [==========] Running 1 test from 1 test suite.
  14. [----------] Global test environment set-up.
  15. [----------] 1 test from HelloTest
  16. [ RUN ] HelloTest.ComposeMessages
  17. [ OK ] HelloTest.ComposeMessages (0 ms)
  18. [----------] 1 test from HelloTest (0 ms total)
  19. [----------] Global test environment tear-down
  20. [==========] 1 test from 1 test suite ran. (0 ms total)
  21. [ PASSED ] 1 test.
  22. hello/1.0: Package '82b6c0c858e739929f74f59c25c187b927d514f3' built
  23. ...

As you can see, the tests were built and run. Let’s use now the tools.build:skip_test configuration in the command line to skip the test building and running:

  1. $ conan create . -c tools.build:skip_test=True -tf=""
  2. ...
  3. [ 50%] Building CXX object CMakeFiles/hello.dir/src/hello.cpp.o
  4. [100%] Linking CXX static library libhello.a
  5. [100%] Built target hello
  6. hello/1.0: Package '82b6c0c858e739929f74f59c25c187b927d514f3' built
  7. ...

You can see now that only the library target was built and that no tests were built or run.

Conditionally patching the source code

If you need to patch the source code the recommended approach is to do that in the source() method. Sometimes, if that patch depends on settings or options, you have to use the build() method to apply patches to the source code before launching the build. There are several ways to do this in Conan. One of them would be using the replace_in_file tool:

  1. import os
  2. from conan import ConanFile
  3. from conan.tools.files import replace_in_file
  4. class helloRecipe(ConanFile):
  5. name = "hello"
  6. version = "1.0"
  7. # Binary configuration
  8. settings = "os", "compiler", "build_type", "arch"
  9. options = {"shared": [True, False], "fPIC": [True, False]}
  10. default_options = {"shared": False, "fPIC": True}
  11. def build(self):
  12. replace_in_file(self, os.path.join(self.source_folder, "src", "hello.cpp"),
  13. "Hello World",
  14. "Hello {} Friends".format("Shared" if self.options.shared else "Static"))

Please, note that patching in build() should be avoided if possible and only be done for very particular cases as it will make more difficult to develop your packages locally (we will explain more about this in the local development flow section later)

Conditionally select your build system

It’s not uncommon that some packages need one build system or another depending on the platform we are building on. For example, the hello library could build in Windows using CMake and in Linux and MacOS using Autotools. This can be easily handled in the build() method like this:

  1. ...
  2. class helloRecipe(ConanFile):
  3. name = "hello"
  4. version = "1.0"
  5. # Binary configuration
  6. settings = "os", "compiler", "build_type", "arch"
  7. options = {"shared": [True, False], "fPIC": [True, False]}
  8. default_options = {"shared": False, "fPIC": True}
  9. ...
  10. def generate(self):
  11. if self.settings.os == "Windows":
  12. tc = CMakeToolchain(self)
  13. tc.generate()
  14. deps = CMakeDeps(self)
  15. deps.generate()
  16. else:
  17. tc = AutotoolsToolchain(self)
  18. tc.generate()
  19. deps = PkgConfigDeps(self)
  20. deps.generate()
  21. ...
  22. def build(self):
  23. if self.settings.os == "Windows":
  24. cmake = CMake(self)
  25. cmake.configure()
  26. cmake.build()
  27. else:
  28. autotools = Autotools(self)
  29. autotools.autoreconf()
  30. autotools.configure()
  31. autotools.make()
  32. ...

See also