Update 2023-08-17: This is now a feature in bazel, see https://github.com/bazelbuild/bazel/issues/18766 for details. It is available starting bazel version 6.3.0. Use
additional_compiler_input
parameter tocc_library
and other C++ rules to provide arbitrary files.
Adapted from the bazel-discuss
mailing list.
I have a cc_library.
I want to set “-fsanitize-ignorelist” to point to a file in my repo.
E.g., I have:
foo.cc BUILD.bazel ignorelist.txt
and in BUILD.bazel:
cc_library( name = "foo", copts = ["-fsanitize-ignorelist=" <TODO what goes here?>], srcs = ["foo.cpp"], )
I’ve tried setting ignorelist.txt as a data dependency, and then referring to it with $(location), but that doesn’t work. I get: clang: error: no such file or directory: ‘bazel-out/k8-fastbuild/ignorelist.txt’
I suspect the issue is that a data
dependency is not available in the sandbox used for compilation.
As seen at: As can be seen from documentation for data = ...
:
“…Files needed by this rule at runtime. "
So, indeed, the targets mentioned in data
are not available in the sandbox at compile time.
What I did was to rename the file such that its name ends with “.h”. It can then be used in the hdrs
, and $location
will work, and it will be available during compilation.
Like so:
cc_library(
name = "foo",
copts = ["-fsanitize-ignorelist=\"$(location ignorelist.txt.h)\""],
srcs = [ "foo.cpp" ],
hdrs = [ "ignorelist.txt.h" ], # <-- the .h is the trick
)
As you can see, the original file ignorelist.txt
is renamed to ignorelist.txt.h
This makes it possible to mention the file in the hdrs = [...]
section. This works because hdrs
do not get added into the produced command line for compiling the cc_library
, but they do have to be present in the sandbox. As a result the behavior is as expected, and the the file’s extension .h
allows it to appear in hdrs
. A drawback is that your non-header file now has an extension .h
but I found it not to be a very confusing point.
Trying this with srcs
or deps
instead would not work.
- Anything mentioned in
srcs
will end up in the compiler’s command line; - Anything in
deps
needs to have aCcInfo
provider (which our file doesn’t have), and also ends up in the compiler’s command line.
Happy to learn about a canonical way to do this. This feels like a hack, but on the other hand seems to be the only way to achieve the needed result. Perhaps it is worth reporting as a feature request?