Search code examples
cmakemeson-buildfetchcontent

What is the meson equivalent of cmake's `FetchContent`?


How would I fetch a dependency from GitHub in meson? I am trying to convert the following cmake snippet into meson

FetchContent_Declare(
  some_dep
  GIT_REPOSITORY https://github.com/some/repo
  GIT_TAG        sometag
  SOURCE_SUBDIR  src
)

FetchContent_MakeAvailable(some_dep)

Note that this dependency may not be using meson as its build system.


Solution

  • The meson equivalent is subprojects and the wrap dependency system. Here a simple example:

    • subprojects/fmt.wrap:
      [wrap-file]
      directory = fmt-7.1.3
      source_url = https://github.com/fmtlib/fmt/archive/7.1.3.tar.gz
      source_filename = fmt-7.1.3.tar.gz
      source_hash = 5cae7072042b3043e12d53d50ef404bbb76949dad1de368d7f993a15c8c05ecc
      patch_url = https://wrapdb.mesonbuild.com/v1/projects/fmt/7.1.3/1/get_zip
      patch_filename = fmt-7.1.3-1-wrap.zip
      patch_hash = 6eb951a51806fd6ffd596064825c39b844c1fe1799840ef507b61a53dba08213
      
      [provide]
      fmt = fmt_dep
      

      It is a meson convention that the directory must be named subprojects and be a top-level directory.

    • meson.build:
      project('demo', 'cpp')
      
      fmt_dep = dependency('fmt-7', required: false)
      if not fmt_dep.found()
        fmt_proj = subproject('fmt')
        fmt_dep = fmt_proj.get_variable('fmt_dep')
      endif
      
      executable('demo', 'main.cpp', dependencies: fmt_dep, install: true)
      
    • main.cpp:
      #include <fmt/core.h>
      int main() {
          fmt::print("Hello, world!\n");
      }
      

    This will search libfmt on your system and fallback to downloading it as specified in the wrap file. The subproject() function requires a meson.build file in the root directory, similar to how FetchContent expects a CMakeLists.txt. If the respective project does not have meson build files, you can provide patches through the patch_* or diff_files properties in the wrap file. This is e.g. the case for libfmt does not have meson build files. You can also use [wrap-git] instead of [wrap-file] to specify a git repository instead of a release tarball. Please refer to the documentation.

    Tip: The meson developers maintain the Wrap DB, where you can find wrap files for some common libraries/projects.