Skip to content

Zig Packages & Dependencies

Sooner or later you’ll want code you didn’t write: a command-line parser, a JSON5 reader, a game library. Zig has a package manager built into zig build, and it works differently from npm, pip or cargo: there’s no central registry. A package is just a folder with a build.zig.zon file, you point at it with a URL, and Zig checks that what it downloaded is exactly what you expected using a hash. This page builds a tiny package, uses it from another project, and then shows how the same steps work with packages from the internet.

Everything here was checked with Zig 0.17.1. It builds on Zig Modules & Imports and Zig Build System, so read those first if addModule and b.step are new to you.

A package is a folder with a build.zig.zon in it (and almost always a build.zig). Every project made with zig init is already a package. The .zon file (Zig Object Notation, Zig’s syntax for data) describes it:

.{
.name = .roman,
.version = "0.1.0",
.fingerprint = 0xb096ed2d589c0210, // Changing this has security and trust implications.
.minimum_zig_version = "0.17.1",
.dependencies = .{},
.paths = .{
"build.zig",
"build.zig.zon",
"src",
"LICENSE",
},
}
Field What it means
.name The package’s name, written as an enum literal (.roman, not "roman").
.version Its version, in the usual major.minor.patch form.
.fingerprint A random id Zig picks once, when the package is created. Don’t change it, and don’t copy it into a new project: it’s how Zig tells two packages apart.
.minimum_zig_version The oldest Zig it’s meant to work with.
.dependencies The packages this one uses. Empty for now.
.paths Which files belong to the package. Only these are hashed and kept when someone else downloads it.

A package can contain modules, programs and libraries. People who use your package get at its modules through your build.zig, so packages and build.zig always go together.

Here’s a package that turns numbers into Roman numerals. Its folder:

roman/
├── build.zig
├── build.zig.zon
└── src/
└── roman.zig

The code is ordinary Zig, with a test:

//! Turn numbers into Roman numerals.
const std = @import("std");
const values = [_]u16{ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
const letters = [_][]const u8{ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
/// Writes `n` as a Roman numeral into `buf` and returns the part it used.
/// `n` must be between 1 and 3999.
pub fn toRoman(buf: []u8, n: u16) error{ OutOfRange, NoSpaceLeft }![]const u8 {
if (n == 0 or n > 3999) return error.OutOfRange;
var rest = n;
var len: usize = 0;
for (values, letters) |value, text| {
while (rest >= value) : (rest -= value) {
if (len + text.len > buf.len) return error.NoSpaceLeft;
@memcpy(buf[len..][0..text.len], text);
len += text.len;
}
}
return buf[0..len];
}
test toRoman {
var buf: [16]u8 = undefined;
try std.testing.expectEqualStrings("MMXXVI", try toRoman(&buf, 2026));
try std.testing.expectEqualStrings("XIV", try toRoman(&buf, 14));
try std.testing.expectError(error.OutOfRange, toRoman(&buf, 0));
}

Output:

All 1 tests passed.

The build.zig is what makes it a package other people can use. The key line is b.addModule, which publishes the module under the name "roman":

const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
// addModule (not createModule): other packages can use this one by name.
const mod = b.addModule("roman", .{
.root_source_file = b.path("src/roman.zig"),
.target = target,
.optimize = optimize,
});
const tests = b.addTest(.{ .root_module = mod });
const test_step = b.step("test", "Run tests");
test_step.dependOn(&b.addRunArtifact(tests).step);
}

Now a second project, app, sitting next to roman:

projects/
├── roman/
└── app/
├── build.zig
├── build.zig.zon
└── src/
└── main.zig

Using a package takes three small edits.

1. Declare it in app/build.zig.zon. For a package on your own disk, give its folder with .path:

.dependencies = .{
.roman = .{ .path = "../roman" },
},

2. Get its module in app/build.zig, and hand it to your program under a name:

const roman_dep = b.dependency("roman", .{
.target = target,
.optimize = optimize,
});
const exe = b.addExecutable(.{
.name = "app",
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
.imports = &.{
.{ .name = "roman", .module = roman_dep.module("roman") },
},
}),
});

b.dependency("roman", ...) finds the package called roman in your .zon file and runs its build.zig. The second argument passes your -Dtarget and -Doptimize choices on to it, so the package is built for the same system and mode as your program. roman_dep.module("roman") then picks out the module it published with addModule.

3. Import it in your code:

const std = @import("std");
const roman = @import("roman");
pub fn main() !void {
var buf: [16]u8 = undefined;
for ([_]u16{ 4, 14, 1999, 2026 }) |n| {
std.debug.print("{d} = {s}\n", .{ n, try roman.toRoman(&buf, n) });
}
}
Terminal window
zig build run

You’ll see:

4 = IV
14 = XIV
1999 = MCMXCIX
2026 = MMXXVI

Notice that the same name, roman, shows up in three places that mean three different things: the key in .dependencies (what b.dependency looks up), the name the package passed to addModule (what .module(...) looks up), and the name in .imports (what your code writes in @import). They’re often the same word, but they don’t have to be. If two packages both export a module called utils, you can import them as "a_utils" and "b_utils".

If build.zig asks for a dependency that build.zig.zon doesn’t list, the build stops before compiling anything. You’ll see something like (trimmed):

info: all dependencies used by build.zig must be declared in corresponding build.zig.zon
panic: no dependency named roman

followed by a stack trace that points at your b.dependency line. The fix is exactly what the first line says.

For a package somewhere else, you use a URL and let zig fetch fill in the .zon entry for you:

Terminal window
zig fetch --save <url>

The URL can point to:

  • a tarball (.tar.gz, .tar.xz and similar), such as the “Download” link of a release on GitHub or Codeberg, or
  • a git repository, written with git+https:// in front, plus # and a tag, branch or commit: git+https://codeberg.org/someone/project#v1.2.0.

To show you real output, here’s zig fetch --save with the roman package packed into a tarball and served from this machine. A URL on the internet gives the same result:

Terminal window
zig fetch --save http://127.0.0.1:8765/roman-0.1.0.tar.gz

--save prints nothing when it works. It downloads the package, works out its hash and adds this to build.zig.zon:

.dependencies = .{
.roman = .{
.url = "http://127.0.0.1:8765/roman-0.1.0.tar.gz",
.hash = "roman-0.1.0-EAKcWKgHAAD9hxJr6kS66Mp_znoUWN6X24zbQF_fevff",
},
},

The entry is named after the package’s own .name. Use --save=othername to pick a different one. build.zig doesn’t change at all: b.dependency("roman", ...) works the same whether the package comes from .path or .url.

For a git URL with a branch or tag, Zig looks up which commit that is right now and saves the commit, so later builds get exactly the same code. A saved git dependency looks like this one (from the official translate-c package’s own build.zig.zon):

.aro = .{
.url = "git+https://codeberg.org/ziglang/arocc?ref=zig-0.17.x#630d99ed60fe61ccabe721f1af60881f8b2adde3",
.hash = "aro-0.0.0-JSD1QvCRNwC2O1Jkop9TO6sXb1U1vhrH8FnYK1VdEMKn",
},

The hash is the package’s name, its version, and then a code computed from the contents of every file listed in its .paths. It’s the real identity of the package. The URL is only one place to get it from.

That gives you two guarantees. If the files at the URL ever change, even by one byte, Zig refuses to use them. And if you already have a package with that hash, Zig doesn’t download it again. Here’s what happens if the hash in build.zig.zon doesn’t match what was downloaded:

./build.zig.zon:7:21: error: hash mismatch: manifest declares roman-0.1.0-EAKcWKgHAAX9hxJr6kS66Mp_znoUWN6X24zbQF_fevff but the fetched package has roman-0.1.0-EAKcWKgHAAD9hxJr6kS66Mp_znoUWN6X24zbQF_fevff

zig fetch <url> without --save just downloads and prints the hash, which is handy for checking a URL before you add it.

Since 0.16, Zig unpacks packages into a zig-pkg/ folder inside your project, one folder per package hash, and also keeps a compressed copy in its global cache (~/.cache/zig/p/ on Linux). So:

  • After the first fetch, building works offline. Delete zig-pkg/ and Zig unpacks it again from the cache, without the network.
  • You can open zig-pkg/ and read (or even edit, to experiment) your dependencies’ code.
  • Most projects put zig-pkg/ in .gitignore, next to zig-out/ and .zig-cache/. Committing it is allowed if you want the code saved with your project.

To download everything a project needs in one go (before a flight, say, or in CI), run zig build --fetch.

Because there’s no registry, you find packages through their READMEs, the Zig community page and search on GitHub or Codeberg. Each README tells you its zig fetch command and the two build.zig lines to add. For example, the README of the popular argument parser zig-clap says to run zig fetch --save with a release tarball URL and then add:

const clap = b.dependency("clap", .{});
exe.root_module.addImport("clap", clap.module("clap"));

addImport is another way to write .imports: it adds one import to a module that already exists.

Here’s the honest part. Zig is still changing between releases, and packages have to keep up. A package built for Zig 0.16 or for the next development version often won’t compile with 0.17.1. When we checked zig-clap for this page, its newest release (0.12.0) was made for Zig 0.16, and its main branch already required a 0.18 development build. That’s normal in the Zig world right now, so before adding a package:

  1. Look at minimum_zig_version in its build.zig.zon, and at the README for a note about versions.
  2. Look for a tag or branch made for your Zig. Some projects keep one per release, like the official translate-c package’s zig-0.17.x branch.
  3. If nothing fits, pin a specific commit (git+https://...#<commit>) that someone has confirmed works, or wait for an update.

zig init --minimal writes .paths = .{""}, which means “everything in the folder”. That’s fine for an app nobody depends on, but for a package it’s a trap: everything includes .zig-cache/ and zig-out/ if they’re lying around, so the hash changes every time you build. List what the package really needs instead:

.paths = .{
"build.zig",
"build.zig.zon",
"src",
"LICENSE",
"README.md",
},

A folder in the list includes everything inside it. Files that aren’t listed are removed when someone downloads your package, which also keeps downloads small.

Add a pub const max = 3999; to roman/src/roman.zig, use it in place of the 3999 inside toRoman, and print it from app’s main.

Hint: with a .path dependency, nothing in app needs updating except main.zig. Use roman.max.

Show solution

In roman/src/roman.zig:

pub const max = 3999;
// in toRoman:
if (n == 0 or n > max) return error.OutOfRange;

In app/src/main.zig, at the end of main:

std.debug.print("largest number: {d}\n", .{roman.max});

zig build run in app now ends with largest number: 3999. A .path dependency is read straight from the folder, so the change shows up on the next build, without zig fetch.

A teammate’s build fails with this:

./build.zig.zon:7:21: error: hash mismatch: manifest declares mylib-1.0.0-AAAA... but the fetched package has mylib-1.0.0-BBBB...

What happened, and what should you do?

Hint: think about what the hash is computed from.

Show solution

The files Zig downloaded from the URL aren’t the files the hash was made from: the contents changed since someone ran zig fetch --save. Don’t paste the new hash in. Find out why it changed (a moved tag, a re-uploaded release, or something worse). If you decide the new code is what you want, run zig fetch --save <url> again on purpose, check the diff of build.zig.zon and commit it.

In app, import the package’s module as numerals instead of roman, without changing the package.

Hint: only one of the three names is yours to choose in build.zig.

Show solution

In app/build.zig, change the import name:

.imports = &.{
.{ .name = "numerals", .module = roman_dep.module("roman") },
},

and in app/src/main.zig write const numerals = @import("numerals"); and numerals.toRoman(...). The .dependencies key and the module name inside the package stay roman.

  • A package is a folder with a build.zig.zon (name, version, fingerprint, dependencies, paths) and a build.zig.
  • A package shares code by publishing a module with b.addModule("name", ...).
  • To use one: list it in .dependencies, call b.dependency("name", .{ .target, .optimize }), and import dep.module("name") through .imports.
  • .path is for packages on your disk; zig fetch --save <url> adds a tarball or git+https package with its hash.
  • The hash comes from the package’s contents. A mismatch means the files changed: find out why before updating it.
  • Packages are unpacked into zig-pkg/ and cached globally, so later builds work offline.
  • Check a package’s minimum_zig_version: many packages target a different Zig than 0.17.1.

Next up: Zig Build Modes, what debug, safe, fast and small keep and drop, with real sizes.

Quick check

1. What does zig fetch --save <url> change in your project?
2. Why does Zig refuse a package whose hash doesn't match build.zig.zon?
3. In roman_dep.module("roman"), where does the name "roman" come from?
4. You're building a library and its build.zig.zon has .paths = .{""}. What's the risk?