How to package a Zig source module
- In a zig source file, write public zig functions or types.
- In
build.zig
add a module for the zig source file. - Create a
build.zig.zon
for the package, include all the source and build files in thepath
.
Example
- file:
src/lib.zig
, publicsay
function.
const std = @import("std");
pub fn say(what: []const u8) void {
std.debug.print("{s}\n", .{what});
}
- file
build.zig
,src/lib.zig
becomesspeak
module.
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
_ = b.addModule("speak", .{
.root_source_file = b.path("src/lib.zig"),
.target = target,
.optimize = optimize,
});
}
- file
build.zig.zon
,
.{
.name = "zig-speak",
.version = "0.1.0",
.paths = .{
"build.zig",
"build.zig.zon",
"src",
},
}
That’s all. Your package is now usable. You can publish it or use it as it is.
Documentation
How to use the package
- Use
zig init
to add an executable or a library that imports the module. - Reference the package in
build.zig.zon
. - In
build.zig
import the module from the package.
Example
- Start a new project
zig-hello
by runningzig init
file src/main.zig
const std = @import("std");
const speak = @import("speak");
pub fn main() void {
speak.say("Hello, Packaged Module!\n");
}
- Run
zig fetch --save ../zig-speak
, this creates or updates the file:build.zig.zon
../zig-speak
is the path to the zig-speak package in our disk.
.{
.name = "zig-hello",
.version = "0.0.0",
.dependencies = .{
.@"zig-speak" = .{
.url = "../zig-speak",
.hash = "12202a...",
},
},
.paths = .{
"",
},
}
- Get the module from the package and import it.
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
// load the "zig-speak" dependency from build.zig.zon
const package = b.dependency("zig-speak", .{
.target = target,
.optimize = optimize,
});
// load the "speak" module from the package
const module = package.module("speak");
const exe = b.addExecutable(.{
.name = "zig-hello",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
// make the module usable as @import("speak")
exe.root_module.addImport("speak", module);
b.installArtifact(exe);
}
Build and run:
> zig build
> zig-out/bin/zig-hello
Hello, Packaged Module!
Use a published package
When calling zig fetch --save
you can provide the git http(s) path of a git repository (other protocols and file formats are possible).
For example you can push the zig-speak
package code to a github repository at https://github.com/username/zig-speak
and access the package as:
zig fetch --save git+https://github.com/username/zig-speak/#HEAD