Search code examples
zig

zig project with multiple exes and libs


I want to setup a zig project that builds several executables and static libs. This is the structure I have in mind:

build.zig
scr/
    exe0/
        depends on lib0, lib1
    exe1/
        depends on lib1
    lib0/
    lib1/

I think one way to do it, is to describe all this in the single build.zig by using something like this:

const lib0 = b.addStaticLibrary("lib0", "src/lib0/index.zig");
const lib1 = b.addStaticLibrary("lib1", "src/lib1/index.zig");

const exe0 = b.addExecutable("exe0", "src/exe0/main.zig");

exe0.linkLibrary(lib0);
exe0.linkLibrary(lib1);

const exe1 = b.addExecutable("exe1", "src/exe1/main.zig");
exe1.linkLibrary(lib1);

Is that a good way? Is it be possible to describe the exes and libs in separate files? How do you link them in that case?

EDIT: I suppose I don't really need static libraries and can actually use packages instead. This would be more zig-like I guess. I'm still interested in the static lib approach, though.


Solution

  • To be able to use the static library approach you would need to explicitly design your entire public interface to use the C ABI. This is pretty constrictive (eg you can't even use slices directly at the API boundary) and if you don't gain any other benefit form this practice somehow, you should eiter use packages or, even more simply, just @import() the files using a relative path.

    About splitting the build.zig file: if you wanted you could create builder functions inside each project so that each can define its own details, if you really want to. I haven't seen people do that in the wild yet though.

    If you want an example of a beefy build.zig file that ties together a few dependences, take a look at Zig showdown: https://github.com/zig-community/Zig-Showdown