Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bazel header file code generator

I am trying to add a code generator to my bazel build by writing a rule to execute the generator, but i am stuck at adding the generated header file as an include path dependency to the library i am trying to build.

The rule looks like this:

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 like this:

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 gcc command line does not add the include path to the generated header file what leads to error: gen_header.h: No such file or directory

like image 586
Jan Avatar asked Sep 23 '15 14:09

Jan


1 Answers

Two possible solutions:

1) Use the output_to_genfiles attribute:

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

Basically it'll put your generated output in bazel-genfiles and cc_* does look there for headers. It's not-very-thoroughly documented here.

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

like image 104
kristina Avatar answered Oct 15 '22 06:10

kristina