How to add examples to a library

I would like to ship multiple examples with my library. Right now, I just have a main.zig which is more like a scratchpad than a proper example file.

How can I configure the build system to have an examples folder in which I can easily run various examples?

3 Likes

Hi, I’ve actually just started assembling a slick Zig project template that I’ve been reusing for both library and executable projects! The library version will have examples like you’re requesting, but, in the meantime, here you go:

const std = @import("std");

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

    // Examples
    const examples_step = b.step("example", "Run examples");

    inline for (EXAMPLE_NAMES) |EXAMPLE_NAME| {
        const example = b.addExecutable(.{
            .name = EXAMPLE_NAME,
            .root_source_file = std.Build.LazyPath.relative(EXAMPLES_DIR ++ EXAMPLE_NAME ++ "/main.zig"),
            .target = target,
            .optimize = optimize,
        });

        const example_run = b.addRunArtifact(example);
        examples_step.dependOn(&example_run.step);
    }

    b.default_step.dependOn(examples_step);
}

const EXAMPLES_DIR = "examples/";

const EXAMPLE_NAMES = &.{
    "example1",
    "example2",
};

You can run all your examples by doing zig build example or just zig build because the “example” step depends on the main one (last line of the build function).

6 Likes

that’s great, thanks a lot!

1 Like

This is great - I was looking for some examples of this too.

Hey @tensorush, would you consider writing some Docs around the build system? We’ve been kicking around that idea for a while but it looks like you’ve really gotten deep into it. I think a lot of people could benefit from some Docs on this subject.

3 Likes

Yeah, sure! I definitely haven’t used every build system trick, but I kinda know the basics and I’d love to figure out more. I’ll start it today then.

3 Likes

This would be fantastic. I would personally love a doc along the lines of “conceptual / concrete migration from Makefiles to zig’s build system” – this is how my mind models a build system.

This is just a suggestion; anything you can come up will be welcome!

1 Like