Use generated code in a bazel build

a 夏天 提交于 2019-12-22 05:35:13

问题


$ python gencpp.py 

This command generates a cpp file foo.cpp in the working directory.

I'd like to run this command in bazel before building to be able to include foo.cpp in cc_binary's srcs attribute.

What I've tried:

genrule(
    name = 'foo',
    outs = ['foo.cpp'],
    cmd = 'python gencpp.py',
)

cc_library(
    srcs = ['foo.cpp'], # tried also with :foo
    ...
)

declared output 'external/somelib/foo.cpp' was not created by genrule. This is probably because the genrule actually didn't create this output, or because the output was a directory and the genrule was run remotely (note that only the contents of declared file outputs are copied from genrules run remotely).

I know that there is a solution that requires gencpp.py to be modified a little bit, but it's not what I'm looking for.


回答1:


Thank's to @kristina for the answer.

I have to copy foo.cpp to outs directory once it's generated.

genrule(
    name = 'foo',
    outs = ['foo.cpp'],
    cmd = """
            python gencpp.py
            cp foo.cpp $@
    """,

)



回答2:


This command generates a cpp file foo.cpp in the working directory.

I would recommend that you change this, so that either:

  • You write the output to a file specified by a command-line flag
  • You write the output to standard output, and redirect standard output to a file

Then your genrule command can be either:

python gencpp.py --outputFile=$@

or

python gencpp.py > $@

(My general personal preference is for the latter, although that can't be used in cases where multiple outputs need to be written.)

respectively.

As Ulf Adams points out:

Bazel runs multiple actions in parallel, and if the same rule is a dependency of a tool as well as of an app, it may try to run both at the same time, and they'd overwrite each other, with potentially very bad results.

So, writing output files which bazel doesn't directly know about is best avoided.



来源:https://stackoverflow.com/questions/42251106/use-generated-code-in-a-bazel-build

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!