Skip to content

Zig Modules & Imports

So far every program in this tutorial has lived in one file. That’s fine for 50 lines, but real programs grow, and at some point you want the math in one file, the parsing in another and main somewhere small and readable. In Zig you do that with one builtin, @import, and one keyword, pub. There’s no include, no module declaration at the top of a file and no __init__.py. This page shows how files find each other, what @import really gives you, and how the bigger unit, a module, fits in.

Everything here was checked with Zig 0.17.1.

Make a folder with two files next to each other. math.zig holds a few helpers:

math.zig
pub const pi = 3.14159;
pub fn add(a: i32, b: i32) i32 {
return a + b;
}
fn double(x: i32) i32 {
return x * 2;
}

main.zig imports it and uses it:

main.zig
const std = @import("std");
const math = @import("math.zig");
pub fn main() void {
std.debug.print("2 + 3 = {d}\n", .{math.add(2, 3)});
std.debug.print("pi is about {d}\n", .{math.pi});
}

Run main.zig. You don’t list math.zig anywhere: Zig follows the @import and compiles it too.

Terminal window
zig run main.zig

You’ll see:

2 + 3 = 5
pi is about 3.14159

Three things are going on:

  • @import("math.zig") takes a path relative to the file that writes it, not to the folder you ran zig from.
  • The result is stored in a constant, math. The name is up to you; const m = @import("math.zig"); works just as well. Most people use the file name.
  • You reach what’s inside with a dot: math.add, math.pi. Exactly like std.debug.print.

Notice that double in math.zig has no pub. Try to call it from main.zig:

std.debug.print("double is {d}\n", .{math.double(4)});

Zig refuses:

main.zig:6:46: error: 'double' is not marked 'pub'
std.debug.print("double is {d}\n", .{math.double(4)});
~~~~^~~~~~~
math.zig:7:1: note: declared here
fn double(x: i32) i32 {
^~~~~~~~~~~~~~~~~~~~~

That’s the whole visibility system. A declaration at the top of a file (a function, a constant, a type) is private to that file unless you write pub in front of it. There’s nothing in between: no protected, no internal, no “visible inside this package”. If another file needs it, make it pub.

This is also why main is always pub fn main. The code that starts your program lives in the standard library (std/start.zig), a different file, and it can only call your main if it’s public.

Here’s the idea that makes Zig’s imports click. When Zig compiles a file, it treats the whole file as if it were wrapped in struct { ... }. So @import("math.zig") gives you a struct type, and pub fn add is just a function declared inside that struct, the same as the methods you wrote in Zig Struct Methods. The language reference on source file structs says exactly this.

The standard library is no different. std is a struct, std.debug is a struct inside it (from the file std/debug.zig), and print is a pub fn in that file. So you can grab a piece of it and give it a short name:

const std = @import("std");
const print = std.debug.print;
const mem = std.mem;
pub fn main() void {
const name = "zigtutorial";
print("starts with zig: {}\n", .{mem.startsWith(u8, name, "zig")});
print("ends with .org: {}\n", .{mem.endsWith(u8, name, ".org")});
}

Output:

starts with zig: true
ends with .org: false

const print = std.debug.print; doesn’t copy anything. It’s a second name for the same function, and you’ll see this pattern at the top of many Zig files.

If a file is a struct, can it have fields? Yes. Such a file is a type you can make values of. Here’s Point.zig:

Point.zig
//! A point on a 2D grid. This file is a struct with two fields.
const Point = @This();
x: f64,
y: f64,
pub fn init(x: f64, y: f64) Point {
return .{ .x = x, .y = y };
}
pub fn distance(self: Point, other: Point) f64 {
const dx = other.x - self.x;
const dy = other.y - self.y;
return @sqrt(dx * dx + dy * dy);
}

x: f64, and y: f64, at the top level are the fields. @This() means “the struct I’m inside”, which here is the file itself, so const Point = @This(); gives the file a name to use in its own code. Using it from another file looks like any other struct:

main.zig
const std = @import("std");
const Point = @import("Point.zig");
pub fn main() void {
const a: Point = .{ .x = 1, .y = 2 };
const b = Point.init(4, 6);
std.debug.print("distance: {d}\n", .{a.distance(b)});
}

You’ll see:

distance: 5

Imports can go into subfolders and back out of them. Here’s a small project:

src/
├── main.zig
├── Point.zig
├── units.zig
└── shapes/
└── shapes.zig

main.zig reaches into the folder, and shapes.zig reaches back up with ..:

src/main.zig
const shapes = @import("shapes/shapes.zig");
// src/shapes/shapes.zig
const units = @import("../units.zig");

Both work, because every path is relative to the file that has the @import in it. Use forward slashes / even on Windows.

There’s one limit. You can’t import a file that sits outside the folder of the file you started with (the root file). If src/main.zig is your starting point and a file tries to reach ../secret.zig outside src/, you get:

src/bad.zig:2:24: error: import of file outside module path
const secret = @import("../secret.zig");
^~~~~~~~~~~~~~~

That folder is the edge of your module, the next idea on this page. Code outside it has to come in as a module of its own.

  • The path must be a plain string literal. @import runs while compiling, so you can’t build the file name from variables at runtime.
  • Importing the same file twice gives the same thing. @import("math.zig") in five files is still one math.zig, compiled once.
  • Files may import each other. If a.zig imports b.zig and b.zig imports a.zig, that’s fine in Zig.
  • Unused code isn’t checked. Zig only looks at code that’s actually used, so a typo in a function nobody calls can hide for a while. Keep tests close to your code to make sure it all gets compiled.

That last point bites with tests. Say math.zig has a test "add" block, and you run zig test main.zig. The test in math.zig doesn’t run, because in a test build nothing calls main, so math.zig is never looked at. Add this to main.zig to pull it in:

test {
_ = math; // also run the tests in math.zig
}

Now zig test main.zig runs both files’ tests:

All 3 tests passed.

(Three: the test "add" in math.zig, a test in main.zig, and this unnamed test block itself.) Projects made with zig init deal with this in build.zig, which you’ll see in Zig Build System.

A file is the small unit. A module is the bigger one: a group of files with one root file at the top, and a name other code can import it by. You’ve used modules since your first program:

  • @import("std"): the standard library is a module named std. Its root file is std/std.zig inside your Zig install. Every module can import it.
  • @import("builtin"): a small module Zig generates for each build, describing what you’re building for. More on it in a moment.
  • Your own program is a module too, the root module, and its root file is the file you passed to zig run (often main.zig).

So @import takes either a file path (it ends in .zig) or a module name (no .zig). The @import section of the language reference lists both forms.

Why have modules at all, when files already work? Because a module can live anywhere: in another folder, or in a package you downloaded. Your code just writes @import("greet") and doesn’t care where the files are. The build decides that.

Here’s a project with a small library outside src/:

build.zig
libs/
└── greet/
└── greet.zig
src/
└── main.zig
libs/greet/greet.zig
const std = @import("std");
pub fn hello(name: []const u8) void {
std.debug.print("Hello, {s}!\n", .{name});
}
src/main.zig
const greet = @import("greet");
pub fn main() void {
greet.hello("modules");
}

src/main.zig can’t use @import("../libs/greet/greet.zig") (that’s outside its module), so build.zig turns greet.zig into a module and hands it to the program under the name "greet":

build.zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
// A module: a root file plus some settings.
const greet = b.createModule(.{
.root_source_file = b.path("libs/greet/greet.zig"),
.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 = &.{
// Inside this module, @import("greet") means the module above.
.{ .name = "greet", .module = greet },
},
}),
});
b.installArtifact(exe);
const run = b.addRunArtifact(exe);
b.step("run", "Run the app").dependOn(&run.step);
}
Terminal window
zig build run

You’ll see:

Hello, modules!

The important line is .imports = &.{ .{ .name = "greet", .module = greet } }. It says “inside this module, @import("greet") means that module”. Don’t worry about the rest of build.zig yet; the next lesson goes through it line by line.

If you try to skip the build file and run zig run src/main.zig, Zig has no idea what "greet" is:

src/main.zig:1:23: error: no module named 'greet' available within module 'main'
const greet = @import("greet");
^~~~~~~

When your module has several files, users of it should only need one import. The root file “re-exports” what it wants to share:

// root.zig, the root file of a library module
pub const Point = @import("Point.zig");
pub const shapes = @import("shapes/shapes.zig");
pub fn version() []const u8 {
return "1.0.0";
}

Anyone who imports this module writes lib.Point or lib.shapes.squareArea(3), and never needs to know how your files are laid out. Only the pub declarations of the root file are visible from outside, so this file is your library’s public face. zig init creates exactly this kind of src/root.zig for you.

@import("builtin") tells your code what it’s being compiled for: the operating system, the CPU, the build mode and more. All of these values are known at compile time, so you can use them in if and switch to pick code for each platform, and the code for other platforms is never compiled in.

Here’s what it prints on a 64-bit Linux PC. On a Mac or on Windows, the OS and CPU lines change.

const std = @import("std");
const builtin = @import("builtin");
pub fn main() void {
std.debug.print("Zig version: {s}\n", .{builtin.zig_version_string});
std.debug.print("OS: {t}\n", .{builtin.target.os.tag});
std.debug.print("CPU: {t}\n", .{builtin.target.cpu.arch});
std.debug.print("build mode: {t}\n", .{builtin.optimize});
std.debug.print("is a test: {}\n", .{builtin.is_test});
}

Output:

Zig version: 0.17.1
OS: linux
CPU: x86_64
build mode: debug
is a test: false

{t} prints the name of an enum value. Want to see everything that’s in builtin? Run zig build-exe main.zig --show-builtin, and Zig prints the whole generated file.

Move celsius into its own file, convert.zig, and call it from main.zig. Keep a helper factor() that returns 1.8 private to convert.zig.

const std = @import("std");
fn factor() f64 {
return 1.8;
}
fn celsius(f: f64) f64 {
return (f - 32) / factor();
}
pub fn main() void {
std.debug.print("{d} F is {d} C\n", .{ 212, celsius(212) });
}

Hint: only celsius needs pub. main.zig then calls it as convert.celsius(212).

Show solution
convert.zig
fn factor() f64 {
return 1.8;
}
pub fn celsius(f: f64) f64 {
return (f - 32) / factor();
}
main.zig
const std = @import("std");
const convert = @import("convert.zig");
pub fn main() void {
std.debug.print("{d} F is {d} C\n", .{ 212, convert.celsius(212) });
}

zig run main.zig prints:

212 F is 100 C

factor stays private, so main.zig can’t call it by mistake, but celsius can still use it because they’re in the same file.

Write Counter.zig, a file with one field count: u32 and two pub functions: init() that returns a counter at 0, and bump(self: *Counter) that adds one. Use it from main.zig.

Hint: start the file with const Counter = @This();. bump changes the counter, so it takes a pointer, and the counter in main must be a var.

Show solution
Counter.zig
const Counter = @This();
count: u32,
pub fn init() Counter {
return .{ .count = 0 };
}
pub fn bump(self: *Counter) void {
self.count += 1;
}
main.zig
const std = @import("std");
const Counter = @import("Counter.zig");
pub fn main() void {
var c = Counter.init();
c.bump();
c.bump();
std.debug.print("count: {d}\n", .{c.count});
}

zig run main.zig prints:

count: 2

The file name is TitleCase because the file is a type with a field. Everything else works exactly like a struct written inside main.zig.

Write a program that prints Hello from Windows!, Hello from macOS! or Hello from Linux! depending on the system it’s built for, and Hello from somewhere else! otherwise.

Hint: switch on builtin.target.os.tag. The tags are .windows, .macos and .linux, and you’ll need an else prong.

Show solution
const std = @import("std");
const builtin = @import("builtin");
pub fn main() void {
const name = switch (builtin.target.os.tag) {
.windows => "Windows",
.macos => "macOS",
.linux => "Linux",
else => "somewhere else",
};
std.debug.print("Hello from {s}!\n", .{name});
}

Output:

Hello from Linux!

The switch is decided while compiling, so a Linux build doesn’t even contain the other strings. Try zig build-exe main.zig -target x86_64-windows and you’ll get a .exe that says “Hello from Windows!”.

  • @import("file.zig") loads another file, with a path relative to the file doing the import. Zig finds and compiles imported files by itself.
  • Top-level declarations are private to their file unless marked pub.
  • Every file is a struct. A file with fields is a type (named in TitleCase, like Point.zig); @This() refers to it.
  • A module is a group of files with a root file and a name. std and builtin are modules, and so is your program.
  • Code outside your module’s folder comes in as a named module, set up with .imports in build.zig.
  • @import("builtin") describes the build. In 0.17 use builtin.target.os.tag and builtin.optimize; builtin.os and builtin.mode are deprecated.
  • zig test main.zig only runs tests in files it actually reaches: add test { _ = math; } to include them.

Next up: Zig Build System, reading the build.zig that zig init makes, line by line, and adding your own steps and options.

Quick check

1. util.zig has fn trim(s: []const u8) []const u8. Why can't main.zig call util.trim(...)?
2. What does @import("Point.zig") return?
3. src/main.zig does @import("../tools/helper.zig") and gets "import of file outside module path". What's the fix?
4. In Zig 0.17, which line checks for a debug build without using deprecated names?