Home > Back-end >  Bazel nested C/C packages, what is the recommended BUILD structure?
Bazel nested C/C packages, what is the recommended BUILD structure?

Time:02-03

Let's say I'm considering a directory structure that looks something like the following for a C project using the bazel build system.

/util
  util.c
  util.h
  /error
    error.c
    error.h
  /math
    math.c
    math.h
    /linalg
      matrix.c
      matrix.h

And, the following additional requirements:

  1. Each directory should be built as a cc_library that contains or relinks its child cc_libraries.
  2. cc_libraries (or their children) will depend on sibling cc_libraries. For example, matrix.c may #include error.h.

Are there ways to preserve this structure when using bazel that don't result in difficult to maintain BUILD files? Are nested packages usable?

/util
  BUILD
  util.c
  util.h
  /error
    BUILD
    error.c
    error.h
  /math
    BUILD
    math.c
    math.h
    /linalg
      BUILD
      matrix.c
      matrix.h

Or, should the folder structure simply take a shallower form?

/util
  BUILD
  util.h
  util.c
/error
  BUILD
  error.c
  error.h
/math
  BUILD
  math.c
  math.h
/linalg
   BUILD
   matrix.c
   matrix.h

CodePudding user response:

I think either approach could work, but I prefer the first.
There's no rule dictating what can (or cannot) depend on what, as long as it's visible to the rule and no cycles are formed. A heuristic like "deps only go sideways or down" doesn't prevent, but can help in avoiding cycles.

Nothing looks particularly difficult to maintain from this example, just specify your deps as needed:

cc_library(
    name = "linalg",
    hdrs = [ "matrix.h" ],
    srcs = [ "matrix.c" ],
    visibility = [ "//visibility:public" ],
    deps = [ "//util/error" ],
)

Etc.

  • Related