1{{#title Bazel, Buck2 — Rust ♡ C++}}
2## Bazel, Buck2, potentially other similar environments
3
4Starlark-based build systems with the ability to compile a code generator and
5invoke it as a `genrule` will run CXX's C++ code generator via its `cxxbridge`
6command line interface.
7
8The tool is packaged as the `cxxbridge-cmd` crate on crates.io or can be built
9from the *gen/cmd/* directory of the CXX GitHub repo.
10
11```console
12$  cargo install cxxbridge-cmd
13
14$  cxxbridge src/bridge.rs --header > path/to/bridge.rs.h
15$  cxxbridge src/bridge.rs > path/to/bridge.rs.cc
16```
17
18The CXX repo maintains working [Bazel] `BUILD` and [Buck2] `BUCK` targets for
19the complete blobstore tutorial (chapter 3) for your reference, tested in CI.
20These aren't meant to be directly what you use in your codebase, but serve as an
21illustration of one possible working pattern.
22
23[Bazel]: https://bazel.build
24[Buck2]: https://buck2.build
25
26```python
27# tools/bazel/rust_cxx_bridge.bzl
28
29load("@bazel_skylib//rules:run_binary.bzl", "run_binary")
30load("@rules_cc//cc:defs.bzl", "cc_library")
31
32def rust_cxx_bridge(name, src, deps = []):
33    native.alias(
34        name = "%s/header" % name,
35        actual = src + ".h",
36    )
37
38    native.alias(
39        name = "%s/source" % name,
40        actual = src + ".cc",
41    )
42
43    run_binary(
44        name = "%s/generated" % name,
45        srcs = [src],
46        outs = [
47            src + ".h",
48            src + ".cc",
49        ],
50        args = [
51            "$(location %s)" % src,
52            "-o",
53            "$(location %s.h)" % src,
54            "-o",
55            "$(location %s.cc)" % src,
56        ],
57        tool = "//:codegen",
58    )
59
60    cc_library(
61        name = name,
62        srcs = [src + ".cc"],
63        deps = deps + [":%s/include" % name],
64    )
65
66    cc_library(
67        name = "%s/include" % name,
68        hdrs = [src + ".h"],
69    )
70```
71
72```python
73# demo/BUILD
74
75load("@rules_cc//cc:defs.bzl", "cc_library")
76load("@rules_rust//rust:defs.bzl", "rust_binary")
77load("//tools/bazel:rust_cxx_bridge.bzl", "rust_cxx_bridge")
78
79rust_binary(
80    name = "demo",
81    srcs = glob(["src/**/*.rs"]),
82    deps = [
83        ":blobstore-sys",
84        ":bridge",
85        "//:cxx",
86    ],
87)
88
89rust_cxx_bridge(
90    name = "bridge",
91    src = "src/main.rs",
92    deps = [":blobstore-include"],
93)
94
95cc_library(
96    name = "blobstore-sys",
97    srcs = ["src/blobstore.cc"],
98    deps = [
99        ":blobstore-include",
100        ":bridge/include",
101    ],
102)
103
104cc_library(
105    name = "blobstore-include",
106    hdrs = ["include/blobstore.h"],
107    deps = ["//:core"],
108)
109```
110