• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1{{#title Bazel, Buck — Rust ♡ C++}}
2## Bazel, Buck, 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 Buck `BUCK` targets for the
19complete blobstore tutorial (chapter 3) for your reference, tested in CI. These
20aren't meant to be directly what you use in your codebase, but serve as an
21illustration of one possible working pattern.
22
23```python
24# tools/bazel/rust_cxx_bridge.bzl
25
26load("@bazel_skylib//rules:run_binary.bzl", "run_binary")
27load("@rules_cc//cc:defs.bzl", "cc_library")
28
29def rust_cxx_bridge(name, src, deps = []):
30    native.alias(
31        name = "%s/header" % name,
32        actual = src + ".h",
33    )
34
35    native.alias(
36        name = "%s/source" % name,
37        actual = src + ".cc",
38    )
39
40    run_binary(
41        name = "%s/generated" % name,
42        srcs = [src],
43        outs = [
44            src + ".h",
45            src + ".cc",
46        ],
47        args = [
48            "$(location %s)" % src,
49            "-o",
50            "$(location %s.h)" % src,
51            "-o",
52            "$(location %s.cc)" % src,
53        ],
54        tool = "//:codegen",
55    )
56
57    cc_library(
58        name = name,
59        srcs = [src + ".cc"],
60        deps = deps + [":%s/include" % name],
61    )
62
63    cc_library(
64        name = "%s/include" % name,
65        hdrs = [src + ".h"],
66    )
67```
68
69```python
70# demo/BUILD
71
72load("@rules_cc//cc:defs.bzl", "cc_library")
73load("//tools/bazel:rust.bzl", "rust_binary")
74load("//tools/bazel:rust_cxx_bridge.bzl", "rust_cxx_bridge")
75
76rust_binary(
77    name = "demo",
78    srcs = glob(["src/**/*.rs"]),
79    deps = [
80        ":blobstore-sys",
81        ":bridge",
82        "//:cxx",
83    ],
84)
85
86rust_cxx_bridge(
87    name = "bridge",
88    src = "src/main.rs",
89    deps = [":blobstore-include"],
90)
91
92cc_library(
93    name = "blobstore-sys",
94    srcs = ["src/blobstore.cc"],
95    deps = [
96        ":blobstore-include",
97        ":bridge/include",
98    ],
99)
100
101cc_library(
102    name = "blobstore-include",
103    hdrs = ["include/blobstore.h"],
104    deps = ["//:core"],
105)
106```
107