Search code examples
javajava-native-interfacebazel

Can't find jni.h if target not declared at the root of workspace


I have a relatively simple BUILD file:

cc_library(
  name = "target",
  srcs = [
    "@local_jdk//:jni_header",
    "@local_jdk//:jni_md_header-linux",
    "hello.cc",
  ],
  includes = [
    "external/local_jdk/include",
    "external/local_jdk/include/linux",
  ],
  linkstatic = 1
)

with an even more simple source file:

#include <jni.h>

If both files live under the workspace root, everything works fine:

$ bazel build //:target
INFO: Analysed target //:target (1 packages loaded).
INFO: Found 1 target...
Target //:target up-to-date:
  bazel-bin/libtarget.a
INFO: Elapsed time: 0.348s, Critical Path: 0.00s
INFO: Build completed successfully, 1 total action

However, if I nest them in a directory, the build fails:

$ bazel build //nested:target
WARNING: /path/to/workspace/nested/BUILD:3:10: in srcs attribute of cc_library rule //nested:target: please do not import '@local_jdk//:include/jni.h' directly. You should either move the file to this package or depend on an appropriate rule there
WARNING: /path/to/workspace/nested/BUILD:3:10: in srcs attribute of cc_library rule //nested:target: please do not import '@local_jdk//:include/linux/jni_md.h' directly. You should either move the file to this package or depend on an appropriate rule there
INFO: Analysed target //nested:target (0 packages loaded).
INFO: Found 1 target...
ERROR: /path/to/workspace/nested/BUILD:1:1: C++ compilation of rule '//nested:target' failed (Exit 1)
nested/hello.cc:1:10: fatal error: jni.h: No such file or directory
 #include <jni.h>
      ^~~~~~~
compilation terminated.
Target //nested:target failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 0.424s, Critical Path: 0.09s
FAILED: Build did NOT complete successfully

Am I holding it wrong?

$ bazel version
Build label: 0.12.0
Build target: bazel-out/k8-opt/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar
Build time: Tue Aug 4 01:22:27 +50246 (1523462001747)
Build timestamp: 1523462001747
Build timestamp as int: 1523462001747

Solution

  • Not a fix, but a workaround...

    In the top-level BUILD file:

    cc_library(
      name = "jni_headers",
      srcs = [
        "@local_jdk//:jni_header",
        "@local_jdk//:jni_md_header-linux",
      ],
      includes = [
        "external/local_jdk/include",
        "external/local_jdk/include/linux",
      ],
      visibility = [
        "//visibility:public",
      ],
    )
    

    In the nested directory:

    cc_library(
      name = "target",
      srcs = [
        "hello.cc",
      ],
      deps = [
        "//:jni_headers",
      ]
      linkstatic = 1
    )