Declaring the layout when creating packages for third-party libraries

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

  1. $ git clone https://github.com/conan-io/examples2.git
  2. $ cd examples2/examples/conanfile/layout/third_party_libraries

If we have this project, intended to create a package for a third-party library whose code is located externally:

  1. .
  2. ├── conanfile.py
  3. └── patches
  4. └── mypatch

The conanfile.py would look like this:

  1. ...
  2. class Pkg(ConanFile):
  3. name = "hello"
  4. version = "1.0"
  5. exports_sources = "patches*"
  6. ...
  7. def layout(self):
  8. cmake_layout(self, src_folder="src")
  9. # if you are declaring your own layout, just declare:
  10. # self.folders.source = "src"
  11. def source(self):
  12. # we are inside a "src" subfolder, as defined by layout
  13. # the downloaded soures will be inside the "src" subfolder
  14. get(self, "https://github.com/conan-io/libhello/archive/refs/heads/main.zip",
  15. strip_root=True)
  16. # Please, be aware that using the head of the branch instead of an immutable tag
  17. # or commit is not a good practice in general as the branch may change the contents
  18. # patching, replacing, happens here
  19. patch(self, patch_file=os.path.join(self.export_sources_folder, "patches/mypatch"))
  20. def build(self):
  21. # If necessary, the build() method also has access to the export_sources_folder
  22. # for example if patching happens in build() instead of source()
  23. #patch(self, patch_file=os.path.join(self.export_sources_folder, "patches/mypatch"))
  24. cmake = CMake(self)
  25. cmake.configure()
  26. cmake.build()
  27. ...

We can see that the ConanFile.export_sources_folder attribute can provide access to the root folder of the sources:

  • Locally it will be the folder where the conanfile.py lives

  • In the cache it will be the “source” folder, that will contain a copy of CMakeLists.txt and patches, while the “source/src” folder will contain the actual downloaded sources.

We can check that everything runs fine now:

  1. $ conan create .
  2. ...
  3. Downloading main.zip
  4. hello/1.0: Unzipping 3.7KB
  5. Unzipping 100 %
  6. ...
  7. [ 50%] Building CXX object CMakeFiles/hello.dir/src/hello.cpp.o
  8. [100%] Linking CXX static library libhello.a
  9. [100%] Built target hello
  10. ...
  11. $ conan list hello/1.0
  12. Local Cache
  13. hello
  14. hello/1.0

See also