Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use generated code in a bazel build

Tags:

bazel

$ 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.

like image 639
Ghilas BELHADJ Avatar asked Feb 15 '17 13:02

Ghilas BELHADJ


2 Answers

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.

like image 181
Andy Turner Avatar answered Nov 12 '22 06:11

Andy Turner


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 $@
    """,

)
like image 35
Ghilas BELHADJ Avatar answered Nov 12 '22 05:11

Ghilas BELHADJ