bazel_iwyu aims to provide C++ developers an convenient way to use IWYU (Include What You Use) with Bazel. It was inspired by the bazel_clang_tidy project. Just like bazel_clang_tidy, you can run IWYU on Bazel C++ targets directly; there is NO need to generate a compilation database first.
[!NOTE] This repository is a fork of com_github_storypku_bazel_iwyu. Since development has stalled on the original repository, we maintain this fork to keep the project active. We want to thank the original author (storypku) for his excellent contributions and foundations.
In your WORKSPACE file, add:
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "bazel_iwyu",
strip_prefix = "bazel_iwyu-<version>",
sha256 = "<sha256sum>",
urls = [
"https://github.com/RealtimeRoboticsGroup/bazel_iwyu/archive/<version>.tar.gz",
],
)
load("@bazel_iwyu//bazel:dependencies.bzl", "bazel_iwyu_dependencies")
bazel_iwyu_dependencies()
In your MODULE.bazel file, add:
bazel_dep(name = "bazel_iwyu", version = "<version>")
.bazelrc:build:iwyu --aspects @bazel_iwyu//:iwyu.bzl%iwyu_aspect
build:iwyu --output_groups=report
(Note: The legacy path @bazel_iwyu//bazel/iwyu:iwyu.bzl%iwyu_aspect remains fully supported for backward compatibility.)
.imp files in a directory, say, bazel/iwyu/mappings, and create a filegroup target for it:# bazel/iwyu/BUILD.bazel
filegroup(
name = "my_mappings",
srcs = glob([
"mappings/*.imp",
]),
)
Then add the following config to your .bazelrc to make it effective:
build:iwyu --@bazel_iwyu//:iwyu_mappings=//bazel/iwyu:my_mappings
.bazelrc like so:build:iwyu --@bazel_iwyu//:iwyu_opts=--verbose=3,--no_fwd_decls,--cxx17ns,--max_line_length=127
To run IWYU on a target:
bazel build --config=iwyu //path/to/pkg:target
The recommended way to apply the suggested fixes is to use bazel run:
bazel run @bazel_iwyu//:fix_includes -- --nosafe_headers < bazel-bin/path/to/pkg/<target>.iwyu.txt
You can also process all reports across your workspace in a single pass:
find -L bazel-bin/ -name "*.iwyu.txt" | xargs cat | bazel run @bazel_iwyu//:fix_includes -- --nosafe_headers
If you prefer to run the script directly on the host:
ln -s bazel-out/../../../external external
fix_includes.py tool:external/bazel_iwyu++iwyu+iwyu_prebuilt_pkg/bin/fix_includes.py --nosafe_headers < bazel-bin/path/to/pkg/<target>.iwyu.txt
external/iwyu_prebuilt_pkg/bin/fix_includes.py --nosafe_headers < bazel-bin/path/to/pkg/<target>.iwyu.txt
x86_64 and aarch64 on Linux, and arm64 on macOS.Issues and PRs are always welcome.