I have a very simple cc_library()
rule that I would like to convert to a Skylark rule.
The cc_library()
rule is:
cc_library(
name = 'cc_library_a',
srcs = [ 'a.c' ],
)
The challange I'm facing is concerining compilation flags that get passed through different methods - for one, the command line. So assume I run the following command line:
# bazel build :a --copt -H
This will add the -H
flag to the compilation command. The question here is how can I get the -H
flag propagated to a Skylark rule?
I have tried the following but it did not work:
def _my_rule(ctx):
_arguments = [ '-c' ]
_arguments.append(ctx.file.src.path)
_arguments += ctx.fragments.cpp.c_options
_arguments += [ '-o', ctx.outputs.out.path ]
ctx.actions.run(
outputs = [ ctx.outputs.out ],
inputs = [ ctx.file.src ],
arguments = _arguments,
executable = ctx.fragments.cpp.compiler_executable,
)
my_rule = rule(
implementation = _my_rule,
attrs = {
'src': attr.label(allow_single_file = True),
},
outputs = {
'out': '%{name}.o',
},
fragments = [ 'cpp' ],
)
The BUILD file content is the following:
load(':rules.bzl', 'my_rule')
my_rule(
name = 'skylark_a',
src = 'a.c',
)
cc_library(
name = 'cc_library_a',
srcs = [ 'a.c' ],
)
The output of building the Skylark rule shows clearly that the --copt
was ignored:
# bazel build skylark_a --copt -H --subcommands
INFO: Found 1 target...
>>>>> # //:skylark_a [action 'SkylarkAction skylark_a.o']
(cd /bazel/jbasila/_bazel_jbasila/4d692aace2e7e1a45eec9fac3922ea8d/execroot/__main__ && \
exec env - \
/usr/bin/gcc -c a.c -o bazel-out/local-fastbuild/bin/skylark_a.o)
INFO: From SkylarkAction skylark_a.o:
a.c: In function 'a':
a.c:3:5: warning: implicit declaration of function 'puts' [-Wimplicit-function-declaration]
puts("a");
^~~~
Target //:skylark_a up-to-date:
bazel-bin/skylark_a.o
INFO: Elapsed time: 0.578s, Critical Path: 0.05s
What am I missing?
Because the --copt -H
parameter is generic to C and C++ you need to get the flags using ctx.fragments.cpp.compiler_options([])
instead. The ctx.fragments.cpp.c_options
code you where using is just for C specific options.
Likewise, there is also a ctx.fragments.cpp.cxx_options([])
function that provides you C++ specific options.