Search code examples
c++bazel

How can you set up dynamically loaded library dependencies in bazel?


Suppose I have a unit test that uses dlopen to load and call code from a provided shared library

int main(int argc, char* argv[]) {
  const char* library = argv[1];
  // calls dlopen with library and does some testing
}

Given the declared library

cc_library(
    name = "a",
    srcs = ["a.cpp"],
    visibility = ["//visibility:public"],
)

Is there any way I can use cc_test to set up the unit test to run with the location of library a passed in as an argument? (Preferably also in a platform independent way so that I don't have to worry about what suffix is used for the library)


Solution

  • You might be able to write a custom skylark rule that accesses runfiles (related discussion here).

    Hacking something together:

    BUILD:

    load("//:foo.bzl", "runfiles")
    
    cc_binary(
        name = "liba.so",
        srcs = [ "a.cc" ],
        linkshared = 1,
    )
    
    runfiles(
        name = "runfiles",
        deps = [ ":liba.so" ],
    )
    

    foo.bzl:

    def _impl(ctx):
      for dep in ctx.attr.deps:
        print(dep.files_to_run.executable.path)
    
    runfiles = rule(
      implementation = _impl,
      attrs = {
        "deps": attr.label_list(allow_files=True),
      }
    )