Zig construct system | KeepCoding
If you initialize challenge scaffold by way of zig build-exe
, it would generate construct.zig
with detailed feedback to assist builders perceive what it does. Essentially the most frequent used instructions are:
zig construct
, default stepset up
is invokedzig construct check
,check
step is invoked
Right here we introduce an important idea in Zig’s construct system: step
. A step describe one job, comparable to compile binary, run the check.
Step.zig defines MakeFn
as step’s important interface:
pub const MakeFn = *const fn (self: *Step, prog_node: *std.Progress.Node) anyerror!void;
All different concrete steps implements it by way of composition with @fieldParentPtr
. If readers do not know this idioms, consult with this post. The next are most typical used steps:
CompileStep
, used to compile binary/static library/static libraryRunStep
, used to execute one programInstallArtifactStep
, used to repeat construct artifacts tozig-out
listing
std.Construct
gives plenty of handy APIs to outline steps and their relation, comparable to:
addExecutable
outline aCompileStep
for software binaryaddTest
outline aCompileStep
for check binaryaddRunArtifact
outline aRunStep
for oneCompileStep
Steps’ relation is constructed utilizing Step.dependOn
operate, and their relation assemble a directed acyclic graph(DAG), which is used to drive the entire construct course of.
Determine above present a easy DAG of steps, steps on the high are particular, and they are often invoked by zig construct ${topLevelStep}
, Construct.step
operate creates such high degree steps.
After clarification above, readers ought to have a deeper perceive what construct.zig
does.
const std = @import("std");
pub fn construct(b: *std.Construct) void {
const goal = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.title = "demo",
.root_source_file = .{ .path = "src/important.zig" },
.goal = goal,
.optimize = optimize,
});
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
const unit_tests = b.addTest(.{
.root_source_file = .{ .path = "src/important.zig" },
.goal = goal,
.optimize = optimize,
});
const run_unit_tests = b.addRunArtifact(unit_tests);
const test_step = b.step("check", "Run unit exams");
test_step.dependOn(&run_unit_tests.step);
}