Bazel and automatically generated cpp / hpp files

I am starting to use Bazel as my C ++ project build system.

However, I am stuck in the following problem:

I am in a scenario where I automatically create a .hpp file.cpp (competent programming) file.

To reproduce my problem, you can simply use this minimal generator:

-- file.sh -- #!/bin/sh echo "int foo();" >> file.hpp echo "#include \"myLib/file.hpp\"\n\nint foo() { return 2017; }" >> file.cpp 

My repo project: (WORKSPACE - empty file)

 β”œβ”€β”€ myLib β”‚  β”œβ”€β”€ BUILD β”‚  └── file.sh └── WORKSPACE 

BUILD File

 genrule( name = "tangle_file", srcs = ["file.sh"], outs = ["file.cpp","file.hpp"], cmd = "./$(location file.sh);cp file.cpp $(@D);cp file.hpp $(@D);" ) cc_library( name = "file", srcs = ["file.cpp"], hdrs = ["file.hpp"], # deps = [":tangle_file"], visibility = ["//bin:__pkg__"], ) 

I have two problems:

Question (A) regarding the part of genrule ():

The fact that I have to use

 cmd = "./$(location file.sh);cp file.cpp $(@D);cp file.hpp $(@D);" 

rather mysterious.

My first attempt:

 cmd = "./$(location file.sh)" 

However, in this case, I get the following error:

The declared output 'myLib / file.cpp' was not created by genrule. This is probably due to the fact that genrule did not actually generate this output, or because the output was a directory, and genrule was started remotely (note that only the contents of the declared output files are copied from the genrules started remotely)

Question (B) on the cc_library () part

I don’t know how to make Bazel aware that the target : the file depends on the target : tangle_file .

If I uncomment:

 deps = [":tangle_file"], 

I get the following error:

in the deps attribute of the cc_library // myLib rule: file: genrule rule '// myLib: tangle_file' is inappropriate here (expected cc_inc_library, cc_library, objc_library, experimental_objc_library or cc_proto_library).

+4
source share
1 answer

Question (A)

The error you see is due to the fact that genrule cmd does not start inside its output directory. If you hardcoded bazel-out/local-fastbuild/genfiles/myLib/file.cpp instead of file.cpp in file.cpp , this will work. However, the recommended approach would be that your script accepts its output directory as an argument.

For instance,

 genrule( name = "tangle_file", srcs = ["file.sh"], outs = ["file.cpp","file.hpp"], cmd = "./$(location file.sh) $(@D)" ) 

and

 #!/bin/sh echo "int foo();" >> $1/file.hpp echo "#include \"myLib/file.hpp\"\n\nint foo() { return 2017; }" >> $1/file.cpp 

Question (B)

The fact that you have

 srcs = ["file.cpp"], hdrs = ["file.hpp"], 

in your cc_library , this is what tells Basel that it depends on genrule , since genrule creates these files. If you want to make it more explicit, you can use shortcut syntax that does the same thing:

 srcs = ["//myLib:file.cpp"], hdrs = ["//myLib:file.hpp"], 
+7
source

Source: https://habr.com/ru/post/1264249/


All Articles