Skip to content

cc_library: Headers listed in srcs are visible to dependents; hello.cpp can include a header not in hdrs #500

@YfLinBelieve

Description

@YfLinBelieve

Description

I observed a confusing behavior with cc_library header visibility. Given the following BUILD file:

load("@rules_cc//cc:defs.bzl", "cc_library")

cc_library(
    name = "test",
    srcs = ["test.c", "test2.h"],
    hdrs = ["test1.h"],
)

cc_library(
    name = "hello",
    srcs = ["hello.cpp"],
    deps = [":test"],
)

In hello.cpp I can successfully do:

#include "test2.h"

even though test2.h is only listed under srcs of the dependency :test, not under hdrs.

Steps to reproduce:

1.Create the BUILD file above.
2.Add a simple test2.h and hello.cpp where hello.cpp includes "test2.h".
3.Build hello: bazel build //path/to:hello.

Actual behavior

The build succeeds. The header test2.h (listed under srcs of :test) is visible to the dependent target hello when included as "test2.h".

Expected behavior / Questions

Is this behavior intended? Should headers listed under srcs of a cc_library be available to dependents?

Environment

Bazel version: 8.3.1
rules_cc version: 0.2.11
Platform: ubuntu 20.04
toolchain: clang 17.0.2

Additional context

If this is intended: best practice for truly-private headers?
If exposing srcs-listed headers to dependents is by design, what is the recommended best practice to ensure private headers cannot be used by external targets?

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions