Zig Build Packaging
A distributable package is a set of installed files that can be handed to another machine as one unit. It holds the program plus the files the program needs beside it.
Install the program
This build file installs the program on the plain build command. The program lands in zig-out under bin.
const std = @import("std");
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{ .name = "app", .root_source_file = b.path("src/main.zig"), .target = b.standardTargetOptions(.{}), .optimize = b.standardOptimizeOption(.{}) });
b.installArtifact(exe);
}
Add a data file
The build file also installs a version file beside the program. The data file lands in share/app under the install prefix.
const std = @import("std");
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{ .name = "app", .root_source_file = b.path("src/main.zig"), .target = b.standardTargetOptions(.{}), .optimize = b.standardOptimizeOption(.{}) });
b.installArtifact(exe);
b.installFile("data.txt", "share/app/data.txt");
}
Run the packaged program
The same build file can also run the program. Its run step prints the program version.
const std = @import("std");
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{ .name = "app", .root_source_file = b.path("src/main.zig"), .target = b.standardTargetOptions(.{}), .optimize = b.standardOptimizeOption(.{}) });
b.installArtifact(exe);
const run_step = b.step("run", "Run the app");
const run = b.addRunArtifact(exe);
run_step.dependOn(&run.step);
}
Example
const std = @import("std");
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{ .name = "app", .root_source_file = b.path("src/main.zig"), .target = b.standardTargetOptions(.{}), .optimize = b.standardOptimizeOption(.{}) });
b.installArtifact(exe);
b.installFile("data.txt", "share/app/data.txt");
const run_step = b.step("run", "Run the app");
const run = b.addRunArtifact(exe);
run_step.dependOn(&run.step);
}
Key points
- Distributable package: a distributable package is a set of installed files handed on as one unit.
- Install step: an install step is the build work that copies files into their install folders.
- Install prefix: an install prefix is the root folder for installed files, named zig-out by default.
- Program folder: the program folder is the bin folder under the install prefix.
- Data file: a data file is a file a program reads, such as a version file.
- Install file step: an install file step is a step that copies one extra file into the package.
The build file installs the program and its version file together. The plain build command copies the program to zig-out/bin and the version file to zig-out/share/app. That folder set is the whole package, ready to hand on.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is a distributable package?