Search code examples
c++bazelbuild-toolsbazel-rules

Bazel | How to copy resources to build directory?


I am making some openGL project, and want to just copy one of my directory into build directory (I store my textures there).

So basically this is what my project structure looks like:

|-WORKSPACE
|-/src/
|  -BUILD
|  -main.cpp
|  -*some folders here*
|-/resources/
|  -BUILD
|  -*some folders here*

All i want is to remain the same relation between directories

This is what i tried:

# src/BUILD file - I use it to build the whole program

cc_binary(
    name = "OpenGL_Project",
    srcs = ["main.cpp"],
    deps = ["//src/renderer:renderer", "//src/scene", "//src/input", "//src/gui"],
    data = ["//resources:resources"]
)

genrule(
    name = "copy_resources",
    srcs = ["//resources"],
    outs = ["resources"],
    cmd = "cp -r $(SRCS) $(OUTS)"
)

And

# resources/BUILD file

filegroup(
    name = "resources",
    srcs = glob(["shaders/**","textures/**"]),
    visibility = ["//visibility:public"],
)

I don't get any errors during build, i tried cleaning it using

bazel clean --expunge

and building again - but it didn't seem to work. Important to add, there is NO resources folder at build directory at all, not that it's in the wrong place.

Do you guys have any ideas what's wrong ?


Solution

  • What you have looks correct, although the copy_resources target isn't necessary. The data dependency on //resources:resources is sufficient for those files to exist in the runfiles directory of //src:OpenGL_Project.

    The files should exist under bazel-bin/src/OpenGL_Project.runfiles. When you bazel run //src:OpenGL_Project, the files resources/shaders/... and resources/textures/... should be accessible relative to the current directory and relative to the RUNFILES_DIR environment variable.

    You can also use the C++ runfiles library here to locate the runfiles in more situations, eg if you run the binary directly with ./bazel-bin/src/OpenGL_Project it will also try to find runfiles in argv[0] + ".runfiles".