Run Specific Examples via build.zig

I want to be able to run a specific example in my projects ‘example/’ dir by doing something like zig build run-example <example name>

I would like:

  • the path to the example zig file to be automatically generated: examples/<example_name>.zig
  • the example file to be built and ran automatically, with command line arguments passed from zig build
  • to expose my library module to the example file (I think I can do this)

Here’s my very broken attempt, to help illustrate my intention:

const std = @import("std");

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

    const mod = b.addModule("arguments", .{
        .root_source_file = b.path("src/root.zig"),
        .target = target,
        .optimize = optimize,
    });

    const example_step = b.step("run-example", "run the specifed example");

    // This doesn't work as the option is not specified to be associated with example_step,
    // and the formatting (which depends on the option) is run regardless of whether the example_step is ran
    const example_name = b.option([]const u8, "example", "run the specified example");
    var path_buf: [32]u8 = undefined;
    const example_path = std.fmt.bufPrint(&path_buf, "examples/{s}.zig", .{example_name}) catch unreachable;

    const example_exe = b.addExecutable(.{
        .name = example_name.?,
        .target = target,
        .optimize = optimize,
        .root_source_file = b.path(example_path),
    });
    example_exe.root_module.addImport("arguments", mod);

    const run_example = b.addRunArtifact(example_exe);

    example_step.dependOn(run_example);
}

Is this even feasible?

1 Like

Have you checked out the following doc? Build system tricks

3 Likes

Here’s an example that’s pretty close to what you’re trying to do:

3 Likes