Expose only part of a project via build.zig(.zon)?

Say I have project A that compiles to a binary. It consists of

  • lib.zig, which has no dependencies, contains library functions used by
  • main.zig which makes the actual program
    • this has some additional dependencies, e.g. for flags parsing etc.

I can expose lib.zig in my build.zig file, by declaring

_ = b.addModule("project_name", .{ .root_source_file = b.path("src/lib.zig")});

so that another project B could use that by

const that_lib = b.dependency("project_name", .{});
const lib_module = that_lib.module("project_name");

in its build.zig and import it like

const that_module = @import("project_name");

The problem I see with this is that the other project B that wishes to use my lib will now fetch the dependencies of the original project A even though they are not used by lib.zig! The obvious solution is to split the original project into two, a library and an application. But that might be kind of awkward for, say, a rather small library?

You can have Lazy Dependencies

Example:

1 Like

that’s an interesting feature, I didn’t know that until now :slight_smile: And the mach example was very helpful. So for me to understand correctly, does this work across projects? Meaning for my example above, if project A doesn’t declare lazy dependencies, then project B will still include any dependency used by project A?

Yes, it works with any tree of packages (projects).


Package A must use lazy dependencies for all the main.zig dependencies.
Package B can use A as non-lazy dependency.
If A build.zig calls lazyDependency for any of main.zig dependencies that means that these dependencies are required, otherwise the lazy dependencies are not fetched.
Every other (non-lazy) dependency is always required and fetched.

oh ok, so IIUC, A would have to “reserve” the dependencies for a step that builds the binary, which B does not want to do. If the “build binary” step would not be “protected” like this the dependencies would be considered required in any case. Is that correct?

Yes, it is correct.

1 Like

Great, thanks for your replies. I will give that a try. And hope stuff does not end up to be so convoluted that I end up splitting library and application ^^

addendum : seems to work nicely :crocodile: !

1 Like