Using a generated header file as a dependecy

Someone asked me today about how to use a generated header as a C++ dependency in Bazel, so I figured I’d write up a quick example.

Create a BUILD file with a genrule that generates the header and a cc_library that wraps it, say, foo/BUILD:

    name = "header-gen",
    outs = ["my-header.h"],
    # This command would probably actually call whatever tool was generat
    cmd = "echo 'int x();' > $@",
    name = "lib",
    hdrs = ["my-header.h"],
    srcs = [""],
    visibility = ["//visibility:public"]

Now you can depend on //foo:lib as you would a “normal” cc_library:

    name = "bin",
    srcs = [""],
    deps = ["//foo:lib"],

And would look like:

#include "foo/my-header.h"
// ...
int main() {
   x();  // Uses x defined in my-header.h.
kristina chodorow's blog