'How to use shell script that generates output files prior to subsequent Bazel build targets

I have a few protobuf files that I'm building with a shell script like so:

proto.sh

#!/usr/bin/env bash

rm -rf ./proto-out
mkdir -p proto-out
protoc -Iproto --cpp_out=./proto-out ./proto/*.proto

However I'm at a loss of what to do in my BUILD file to get the output c++ classes and headers. I'll need to be able to utilize the headers in other dependent libraries later as well. I've tried with genrule like so:

genrule(
    name = "proto-build",
    srcs = glob(["proto/*.proto"]),
    outs = [
        "proto-out/point.pb.h",
        "proto-out/point-geodetic.pb.h",
        "proto-out/point-ned.pb.h",
        "proto-out/point.pb.cc",
        "proto-out/point-geodetic.pb.cc",
        "proto-out/point-ned.pb.cc",
    ],
    cmd = "$(location proto.sh)",
    tools = ["proto.sh"],
    visibility = ["//visibility:public"],
)

cc_library(
    name = "protobuf-common",
    srcs = [
        "proto-out/point.pb.cc",
        "proto-out/point-geodetic.pb.cc",
        "proto-out/point-ned.pb.cc",
    ],
    hdrs = [
        "proto-out/point.pb.h",
        "proto-out/point-geodetic.pb.h",
        "proto-out/point-ned.pb.h",
    ],
    copts = ["--std=c++17"],
    data = [":proto"],
    includes = ["proto-out"],
    visibility = ["//visibility:public"],
)

but there is never any output from the execution of this and the cc_library build of course fails. This is my first day evaluating Bazel as a potential replacement for CMake on my team so any help would be appreciated.

Thanks



Solution 1:[1]

While you can surely make the genrule + cc_library approach work, there are rulesets for proto that does all this for you:

cc_library(
    name = "your_code",
    srcs = ["your_code.cc"],
    deps = [":foo_cc_proto"],
)

cc_proto_library(
    name = "foo_cc_proto",
    deps = [":foo_proto"],
)

proto_library(
    name = "foo_proto",
)

See:

https://bazel-contrib.github.io/SIG-rules-authors/proto-grpc.html

https://docs.bazel.build/versions/main/be/c-cpp.html#cc_proto_library

https://github.com/bazelbuild/rules_proto

https://github.com/bazelbuild/bazel/blob/45f462893df4d55cee19c05ab01e051e229597a3/src/main/protobuf/BUILD#L172-L175

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ahumesky