Search code examples
unit-testingheader-filesbazelbuild-system

Is it possible to share header file only with a cc_test target?


Say I have a package with a single cc_library target and an inner package for tests with a single cc_test target as follows:

mylib/
     BUILD
     mylib.h
     mylib.c
     mylib-private.h
     tests/
         BUILD
         test.c

In order to perform some unit-tests I need access to "private" methods, so I created mylib-private.h which I want to include only in the test code.
Obviously this header should not be part of the library API and should not be shipped with it.

If I add mylib-private to the hdrs of mylib - It'll be visible to all.
If I add mylib-private to srcs of mylib - only mylib can use it...

Is there a way to control the visibility of a single header file?


Solution

  • Not sure what is the official recommended pattern here, but I ended up inclduing both mylib and mylib-tests in the same package, and then they could both add mylib-private to their srcs attribute:

    BUILD:

    cc_library(
        name="mylib",
        hdrs=["mylib.h",],
        srcs=[
            "mylib.c",
            "mylib-private.h"
        ]
    )
    
    cc_test(
        name="mylib-tests",
        srcs=glob([
            "tests/*.c",
            "mylib-private.h"
        ]),
        deps=[
            "//:mylib"
        ]
    )
    

    And the structure:

    mylib/
         BUILD
         mylib.h
         mylib.c
         mylib-private.h
         tests/
             test.c