Bazel Header File Code Generator

I am trying to add a code generator to my bazel assembly by writing a rule to execute the generator, but I am stuck in adding the generated header file as a function of the library path I'm trying to create.

The rule is as follows:

def _impl(ctx): output = ctx.outputs.out input = ctx.attr.defs md_dir = list(ctx.attr.md_dir.files)[0] print("generating", output.path) ctx.action( outputs=[output], progress_message="Generating %s" % md_dir, command="python codegen.py -md_dir %s %s -o %s" % (md_dir.path, input, output.path) ) code_generate = rule( implementation=_impl, attrs={ "defs": attr.string(), "md_dir": attr.label(allow_files=True, single_file=True), "out": attr.output() }, ) 

and the BUILD file:

 load("/common/code_generate", "code_generate") code_generate( name="generate_header_defs", defs="common/header_definition_file", md_dir="header_defs", out="gen_header.h", ) cc_library( name="lnt", hdrs=glob(["*.h"]), srcs=["source.c":gen_header.h"], visibility=["//visibility:public"], deps=["@dep1//:x", "@dep2//:y", "@dep3//:z"], ) 

The code generation works and writes the code to bazel-out / local-fastbuild / bin / common / gen_header.h, but the include path to the generated header file is not added to the gcc command line, which leads to the error: gen_header. h: No such file or directory

+6
source share
1 answer

Two possible solutions:

1) Use the output_to_genfiles attribute:

 code_generate = rule( implementation = _impl, output_to_genfiles = True, attrs = {...} ) 

Basically this will generate your generated output in bazel-genfiles, and cc_ * will look there for the headers. This is not very fully documented here .

2) You can create a genrule that runs python codegen.py (instead of doing it in a Skylark rule).

+7
source

All Articles