Use any source code as a Bazel module

If you are using Bazel and one of the dependencies you need is not in the Bazel Central Registry, but you have the source code, you can still integrate that dependency into Bazel as a module.

The source code can be locally (inside your project) or in any remote location you can access.

I’ll provide an example of integrating Boost.Container version 1.86.0, which at the time of writing is not present in the Bazel Central Registry.

Jump to the end if you want to skip the reading and see the final result.

The concept I’m using is present in other package managers, too, and it’s called overriding. I can declare I want to use a Bazel module, and then I can override Bazel’s behavior when it wants to fetch that module. By default, Bazel searches in its central registry when it sees a dependency declared in MODULE.bazel:

bazel_dep(name = "boost.container", version="1.86.0")

I will tell Bazel to stop looking in its registry and instead use the location I provide for the source code.

There are several ways to do this depending on where the source code is located:

I chose archive_override because the code is on a remote server and, as opposed to git_override, the module’s version is visible inside the URL, thus making it clearer.

The test application

Currently, the test application below uses Boost.Container version 1.83.0, which is present inside Bazel Registry.

Run bazel run //:app and everything works.

# MODULE.bazel

bazel_dep(name = "boost.container", version="1.83.0")
# BUILD.bazel

load("@rules_cc//cc:defs.bzl", "cc_binary")

cc_binary(
    name = "app",
    srcs= [
        "main.cpp",
    ],
    deps = [
        "@boost.container",
    ],
)
// main.cpp

#include <boost/container/vector.hpp>
#include <cassert>

boost::container::vector<int> f() { return {1, 2, 3}; }

int main()
{
    auto numbers = f();
    assert(numbers.size() == 3);
}

I want to use Boost.Container 1.86.0, which is not yet inside the central registry.

Continue reading Use any source code as a Bazel module