liveBook · Manning

Module

As explained in Systems Programming with Zig

A module is a source-code unit that groups related declarations and functionality within a program.

In Zig, a module is a unit of code defined by a root source file and the files it imports recursively. An executable, a system library, or an interface can each be a module. Modules give you a practical boundary for organizing code and its dependencies. section 2.1 section 6.3.1

Use the compiler builtin @import to access a module, usually by assigning the result to a constant. Its accessible declarations can then be reached with dot syntax: std.debug.print names the print function in the debug namespace within std. section 2.1

Listing 2.1 A simple program
const std = @import("std"); #1

pub fn main() void { #2
    const x: i32 = 42; #3
    std.debug.print("{}\n", .{x}); #4
}

This small program imports the standard library as std and uses std.debug.print to print a value. section 2.1

Module boundaries can also keep unrelated dependencies apart. A CHIP-8 interpreter can separate its virtual machine from the interactive runtime that handles keyboard input and graphics. Since linking targets modules, the runtime can carry a heavier dependency without making the VM tests carry it too; that separation can make tests compile slightly faster. section 6.3.1

Listing 6.2 A more modular build script
const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{}); #1
    const optimize = b.standardOptimizeOption(.{}); #1

    const vm_mod = b.createModule(.{ #2
        .root_source_file = b.path("src/vm.zig"),
        .target = target,
        .optimize = optimize,
    });

    const test_mod = b.createModule(.{
        .root_source_file = b.path("src/tests.zig"),
        .target = target,
        .optimize = optimize,
    });
    test_mod.addImport("vm", vm_mod); #3
}

The build script creates separate VM and test modules from root files, then makes the VM available to the test module with addImport. section 6.3.1

The build script can add a test artifact with the test module as its root, create a run step, and attach it to a named test step. This turns the module boundary into a concrete build workflow. section 6.3.1

How Systems Programming with Zig covers it

How deep it goes
Defines modules and imports, then demonstrates module creation, dependency wiring, and test build steps.
Examples
Uses a standard-library print program and a CHIP-8 interpreter with separate VM, runtime, and test modules.
What you can do after
Configure Zig build modules, connect imports, and create a test step.
How it connects
Connects modules to namespaces, linking, build systems, and separation of concerns.

Also explained in

Compare how 44 books explain module →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.