Importing zig dependencies

I’m trying to wrap my head around exactly how to add repos as a dependency in the build system. Currently I have two dummy repos SimpleLib and SimpleExe. I’ve poked and prodded other recent examples and created the current build in SimpleExe as best as I can understand it, however the closest I’ve gotten to a successful build is error: file exists in multiple modules.

At the most basic level, how do I add a dependency from repo A and include it in a file in repo B?

Hello @cohors, welcome to ziggit :slight_smile:

You can import the module from the simple_lib package in exe.

    const simple_module = b.dependency("simple_lib", .{
        .target = target,
        .optimize = optimize,
    }).module("SimpleLib"));

    const exe = b.addExecutable(.{
        .name = "examples",
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
    });
    exe.root_module.addImport("SimpleLib", simple_module);
    b.installArtifact(exe);
2 Likes

That looks like a cleaner solution than what I saw and it builds. Follow up question, build works but zig test src/main.zig fails for module not found. Is there somewhere else I need to import to for tests?

zig test doesn’t use the build system, you have to use zig build test and have a corresponding test step in your build.zig. The sample build.zig created by zig init has such a test step. To that test step you add imports just like you do for the exe.

2 Likes

got it, thanks.

1 Like

This is very useful. I wonder why I can’t find this in official documentation. Only landed here after a few attempts of googling.

I wonder why the name is repeated 3 times? What are they for?

const simple_module = b.dependency("simple_lib", .{
// I assume "simple_lib" must match the name in build.zig.zon?
    .target = target,
    .optimize = optimize,
}).module("SimpleLib")); // what's this one for?
...
exe.root_module.addImport("SimpleLib", simple_module);
// I assume this is the one you use in your @import?
1 Like

There are 3 names for:

  • the package name ("simple_lib"),
  • the module name as exposed from the package ("SimpleLib"),
  • and the name for your code: import("SimpleLib").

See also in the ziggit documentation section: How to package a zig source module and how to use it
Zig official documentation exists for:

Welcome to ziggit :slight_smile:

4 Likes

zig test doesn’t use the build system

Does it mean that it’s impossible to debug separate zig file with dependencies?

It’s possible to use zig test with modules, but you will need to manually set up all the module relationships by specifying -M and --dep arguments:

This will quickly grow complicated if multiple modules and module-specific options are involved. It’s generally easier to just use the build system.

2 Likes

so b.addTest(.{… should be called for every zig file with test
with different name