Bazel C++ 规则cc_liibrary:为什么目标可以访问未通过 hdrs 公开的依赖项的标头?

问题描述

可以在 https://github.com/versemonger/bazel-test

找到示例存储库

解决方法

Bazel 默认不实现任何头部隐私检查。但是,在 clang 和最新版本的 Bazel 下,可以使用 layering_check 功能启用所谓的“分层检查”验证。例如,使用 OP 的示例存储库和 Bazel 4.0.0,我看到:

$ CC=clang bazel build //sub --features layering_check
INFO: Analyzed target //sub:sub (16 packages loaded,56 targets configured).
INFO: Found 1 target...
ERROR: sub/BUILD:3:10: Compiling sub/greet.cpp failed: (Exit 1): clang failed: error executing command /usr/bin/clang -U_FORTIFY_SOURCE -fstack-protector -Wall -Wthread-safety -Wself-assign -fcolor-diagnostics -fno-omit-frame-pointer '-std=c++0x' -MD -MF ... (remaining 28 argument(s) skipped)

Use --sandbox_debug to see verbose messages from the sandbox clang failed: error executing command /usr/bin/clang -U_FORTIFY_SOURCE -fstack-protector -Wall -Wthread-safety -Wself-assign -fcolor-diagnostics -fno-omit-frame-pointer '-std=c++0x' -MD -MF ... (remaining 28 argument(s) skipped)

Use --sandbox_debug to see verbose messages from the sandbox
sub/greet.cpp:1:10: error: use of private header from outside its module: 'f.h' [-Wprivate-header]
#include "f.h"
         ^

layering_check 也可以通过在 features = ['layering_check'] 文件中设置 BUILD 来针对每个目标启用。