Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 37 ยท C Interop and Build System

Packages and Modules

Organize Zig code with files as structs, @import, pub, and root modules, then add dependencies with build.zig.zon, zig fetch, content hashes and addImport, with a runnable hash stand-in.

As soon as a program outgrows one file you need two things: a way to split code into files and modules, and a way to use code written by other people, called packages. Zig keeps both simple. Files are structs, modules are named import roots, and packages are source code downloaded, hashed and compiled together with your project. There is no central binary repository: a dependency is a URL plus a content hash.

Every file is a struct

When you write const geometry = @import("geometry.zig");, Zig reads that file and treats its top-level declarations as the fields and declarations of an anonymous struct. So a file is a namespace you can pass around:

ZIG
// geometry.zig
pub const Point = struct { x: f32, y: f32 };

pub fn distance(a: Point, b: Point) f32 {
    const dx = a.x - b.x;
    const dy = a.y - b.y;
    return @sqrt(dx * dx + dy * dy);
}

fn helper() void {} // private: invisible outside this file
ZIG
// main.zig
const std = @import("std");
const geometry = @import("geometry.zig");

pub fn main() void {
    const d = geometry.distance(.{ .x = 0, .y = 0 }, .{ .x = 3, .y = 4 });
    std.debug.print("{d}\n", .{d}); // 5
}

Rules:

  • Only pub declarations can be used from another file. Everything else is private to its file.
  • Paths are relative to the importing file. @import("../util/strings.zig") works.
  • Imports are lazy: code in a file is analyzed only if something uses it. Unused functions are never compiled, so errors in them are not reported until used.
  • A file cannot import files outside its module (the directory tree under the module's root file). To share code across that boundary, make it a named module, below.
  • If a file is mostly one type, it can define fields at the top level, and the whole file becomes that struct: const Stack = @import("Stack.zig");. File names starting with an uppercase letter are the convention for such files.

Re-exporting

To build a library with one entry file, re-export parts from it:

ZIG
// root.zig
pub const geometry = @import("geometry.zig");
pub const Point = geometry.Point;

Callers then write @import("mylib").Point. (The old usingnamespace that did this for whole files has been removed from the language.)

Named modules

Besides file imports there are named imports: @import("std"), @import("builtin") and any module you register in build.zig with addImport:

ZIG
const geometry_mod = b.createModule(.{
    .root_source_file = b.path("src/geometry/root.zig"),
    .target = target,
    .optimize = optimize,
});
exe.root_module.addImport("geometry", geometry_mod);

Now any file in the executable can say @import("geometry"). A module has its own root file and its own imports, so it works as the unit of reuse inside a project: a library, a test harness, generated code. The compiler also treats the module as the boundary for relative file imports, as mentioned above.

Packages and build.zig.zon

A package is a directory with a build.zig and a build.zig.zon file. ZON ("Zig Object Notation") is Zig's data syntax: a struct literal.

ZIG
// build.zig.zon
.{
    .name = .myapp,
    .version = "0.1.0",
    .minimum_zig_version = "0.15.0",
    .dependencies = .{
        .zigimg = .{
            .url = "https://github.com/example/zigimg/archive/refs/tags/v0.1.0.tar.gz",
            .hash = "1220abcdef...",
        },
    },
    .paths = .{ "build.zig", "build.zig.zon", "src" },
}

You rarely write the hash yourself:

TEXT
zig fetch --save https://example.com/zigimg-v0.1.0.tar.gz

downloads the archive, computes its content hash and adds the entry to build.zig.zon. The hash is what identifies the package; the URL is only where to find it. If the file at the URL changes, the hash no longer matches and the build fails, so a compromised or silently updated download cannot sneak in. Downloaded packages are cached globally, so the second project that uses them builds offline. Local packages use .path = "../mylib" instead of a URL.

Use the dependency in build.zig:

ZIG
const zigimg = b.dependency("zigimg", .{
    .target = target,
    .optimize = optimize,
});
exe.root_module.addImport("zigimg", zigimg.module("zigimg"));

The package's own build.zig decides which modules it exposes (b.addModule("zigimg", ...)). Your code then calls @import("zigimg"). Passing target and optimize ensures the dependency is built for the same platform and mode as your program.

Publishing a package

  1. Give the package a build.zig that exposes a module with b.addModule.
  2. Make a build.zig.zon with a name, version and the .paths list of files to include.
  3. Tag a release on a Git host and share the archive URL. Users run zig fetch --save <url>.

There is no registry to approve you: package discovery sites index public repositories.

Good habits

  • Keep a library's public surface tiny: one root.zig that re-exports.
  • Pin versions with the hash and update on purpose; zig fetch --save again for a new version.
  • Prefer few dependencies. Packages are source code compiled into your binary, so each one adds build time and trust.
  • Test a module in isolation with its own addTest.
flowchart TD
  A["main.zig"] -->|"@import('geometry.zig')"| B["geometry.zig<br/>(file = struct)"]
  A -->|"@import('zigimg')"| C["named module<br/>from build.zig"]
  C --> D["package in build.zig.zon<br/>url + hash"]

Caption: file imports stay inside a module; named imports reach other modules and packages.

A runnable stand-in

The idea that makes packages safe is the content hash. Go's crypto/sha256 lets us act it out: a "package" is bytes, the manifest remembers the expected hash, and a changed download is rejected. This is a stand-in for the concept; Zig uses its own hash format.

Go Stand-in: verifying a package by content hash (Go)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Common mistakes

  • Importing a file from outside the module root and getting "import of file outside module path"; promote it to a named module.
  • Forgetting pub, then wondering why a declaration is "not accessible".
  • Editing the URL in build.zig.zon but not the hash: use zig fetch --save instead.
  • Not passing target/optimize to b.dependency, which builds the dependency for the wrong settings.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a Zig source file when imported with @import?

    Each file is treated as an anonymous struct whose pub declarations you can access.
  2. 2. What identifies a package dependency in build.zig.zon?

    The hash identifies the exact content; the URL is just where to download it. If content changes, the hash check fails.
  3. 3. Which command adds a dependency and records its hash?

    zig fetch --save downloads the package, computes the hash and edits build.zig.zon.
  4. 4. How do you let all files in an executable do @import("geometry")?

    addImport registers a named module for the importing module.

Summary

  • Files are structs; only pub declarations are visible outside; relative imports cannot leave a module.
  • Named modules are registered with addImport in build.zig.
  • Packages are declared in build.zig.zon with a URL and content hash, added by zig fetch --save, and used via b.dependency.
  • Keep the public surface small and dependencies few.

Next: Threads and synchronization