Zig ways of the code reusing

I started a new Zig project and realized, that some required functionality was already developed in my another project (repo).

I have some options:

  • [cut&paste way] Copy sources to the new repo
  • [usual way] Create new project, move reusable code to it and add dependency to old and new projects
  • [Zig way?] - Add dependency(old project) to build.zig.zon of new one - as far as I understand only used code will be add to result

Did I miss sumething?

Is there ZIg way of code reusing?

1 Like

IMHO: just use the package manager.

For instance I have an emulator project here:

…and at some later point I started another experimental project to run those emulators in a terminal:

The chipz project is already split into a couple of modules which are automatically available in upstream projects:

In the upstream project I have a dependency to chipz:

…and I import the chipz module like this:

…and then import a specific submodule of chipz like this:

…Zig itself will only compile code that’s actually used into such an emulator executable, so no problems there.

But one problem I’ll need to fix is that my chipz build.zig is setup in a way to always build everything, e.g. when only the chipz dependency is used by an upstream project, it will also build all the emulator exes from the chipz project, plus code-generation and benchmark tools, even though those things are useless for the upstream project… but that’s on me, I was just dumb when writing the chipz build.zig.

2 Likes

and this is not duplication?

pub const chips = @import("chips");
pub const common = @import("common");
pub const systems = @import("systems");
pub const host = @import("host");
   const mod_chipz = b.addModule("chipz", .{
        .root_source_file = b.path("src/chipz.zig"),
        .target = target,
        .optimize = optimize,
        .imports = &.{
            .{ .name = "common", .module = mod_common },
            .{ .name = "chips", .module = mod_chips },
            .{ .name = "systems", .module = mod_systems },
            .{ .name = "host", .module = mod_host },
        },
    });

If you can come up with a better way to re-export all submodules under a common chipz module than be my guest :slight_smile: (I tried a couple of different options, but this was the cleanest).

IIRC the top-level chipz module was only added after making the chipz project available as dependency. The individual module definitions are needed for cross-import within the project, while for use as dependency only the top-level chipz module is relevant.

An import alone doesn’t cause compilation of the entire import, only of the parts that are actually used, otherwise any @import("std") in regular Zig code would explode build times.

1 Like