Created
January 9, 2024 21:39
-
-
Save morgangallant/c8aa4d1ee9fcf7eb965e1148d9cdfcd2 to your computer and use it in GitHub Desktop.
build.zig file which automatically creates executables for all .main.zig files in src/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
pub fn build(b: *std.Build) !void { | |
const target = b.standardTargetOptions(.{}); | |
const optimize = b.standardOptimizeOption(.{}); | |
// For every `.main.zig` file in src (recursive), we export an executable | |
// using it as the root source file. This means one Zig project can be used | |
// to build multiple end-executables (and they can all share code!). | |
{ | |
const src_root = "src/"; | |
var src_dir = try std.fs.cwd().openDir(src_root, .{ .iterate = true }); | |
defer src_dir.close(); | |
var walker = try src_dir.walk(b.allocator); | |
defer walker.deinit(); | |
while (try walker.next()) |entry| { | |
if (!std.mem.endsWith(u8, entry.path, ".main.zig")) continue; | |
const path = try std.fs.path.join(b.allocator, &[_][]const u8{ | |
src_root, | |
entry.path, | |
}); | |
const exe_name = try b.allocator.dupe(u8, entry.basename[0 .. entry.basename.len - 9]); | |
const exe = b.addExecutable(.{ | |
.name = exe_name, | |
.root_source_file = .{ .path = path }, | |
.target = target, | |
.optimize = optimize, | |
}); | |
exe.linkLibC(); | |
b.installArtifact(exe); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment