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>")- Add the following to your
.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.)
- Custom Mappings: If you would like to use your own IWYU mappings, put all your
.impfiles in a directory, say,bazel/iwyu/mappings, and create afilegrouptarget 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- Custom Options: If custom IWYU options should be used, configure them in your
.bazelrclike so:
build:iwyu --@bazel_iwyu//:iwyu_opts=--verbose=3,--no_fwd_decls,--cxx17ns,--max_line_length=127To run IWYU on a target:
bazel build --config=iwyu //path/to/pkg:targetThe 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.txtYou 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_headersIf you prefer to run the script directly on the host:
- Create a top-level "external" symlink:
ln -s bazel-out/../../../external external- Run the
fix_includes.pytool:
- Bzlmod:
external/bazel_iwyu++iwyu+iwyu_prebuilt_pkg/bin/fix_includes.py --nosafe_headers < bazel-bin/path/to/pkg/<target>.iwyu.txt
- WORKSPACE (Legacy):
external/iwyu_prebuilt_pkg/bin/fix_includes.py --nosafe_headers < bazel-bin/path/to/pkg/<target>.iwyu.txt
- Support
x86_64andaarch64on Linux, andarm64on macOS. - No compilation database needed.
- Support custom IWYU mapping files.
- Support custom IWYU options.
Issues and PRs are always welcome.