Bazel execute python script before running cc_binary

167 Views Asked by At

I am trying to create a bazel target which will run c++ binary from .cpp file, which is dynamically generated by python script.

Lets say I have generator.py which creates in the dir a generated.cpp file.

My rules looks like this:

# py_binary(
#     name = "generator",
#     srcs = [
#         "src/generator.py"
#     ],
#     main = "src/generator.py",
#     data = [
#         ":generator_inputs",
#     ],
#     imports = ["."],
# )
   
# cc_binary(
#     name = "run_generated_cpp",
#     srcs = ["src/generated.cpp"],
#     deps = [
#         "//cpp_lib",
#     ]
# )

How Can I combine this 2 targets into 1 ? So that executing cc_binary has a preprocess step of generating file from py script.

1

There are 1 best solutions below

2
Troy Carlson On

You probably want to use a genrule. Genrules enable you to execute a binary during the build and they can produce outputs which other rules can declare as inputs. I didn't actually test the code below, but the general idea is you define your generator binary and specify that target in the tools list of a genrule target, use the $(location) helper to invoke the tool in the cmd field of the genrule, and declare the generated files as outputs of the genrule. Once declared, these can be used as inputs to other rules.

py_binary(
    name = "generator",
    srcs = [
        "src/generator.py"
    ],
    main = "src/generator.py",
    data = [
        ":generator_inputs",
    ],
    imports = ["."],
)

genrule(
    name = "generated_cpp_sources",
    outs = ["src/generated.cpp"],
    tools = [":generator"],
    cmd = "$(location :generator)"
)
   
cc_binary(
    name = "run_generated_cpp",
    srcs = ["src/generated.cpp"],
    deps = [
        "//cpp_lib",
    ]
)