Cross platform main.zig / std.process.Init

I know this is probably a very simple question, but is there a single consistent way to write main.zig across MacOS and Linux (or just cross platform in general really)? For Linux I found this works:

pub fn main(init: std.process.Init) !void {
    // Initialise allocator
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator: std.mem.Allocator = gpa.allocator();

    // Read Argv for file path
    var args = try init.minimal.args.iterateAllocator(allocator);
    _ = args.skip();
    const path: [:0]const u8 = args.next() orelse return error.MissingArgs;

    // Initialise IO implementation
    var threaded: std.Io.Threaded = .init(allocator, .{ .environ = init.minimal.environ });
    const io = threaded.io();
    defer threaded.deinit();

    // etc
}

Whereas when I try to do the same thing on Mac I get “error: root source file struct ‘process’ has no member named ‘Init’” and have to do something like this instead:

pub fn main() !void {
    // Initialise allocator
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator: std.mem.Allocator = gpa.allocator();

    // Read Argv for file path
    var args = std.process.args();
    _ = args.skip();
    const path: [:0]const u8 = args.next() orelse return error.MissingArgs;

    // Initialise IO implementation
    var threaded: std.Io.Threaded = .init(allocator, .{});
    const io = threaded.io();
    defer threaded.deinit();

    // etc
}

Any help would be greatly appreciated!

That sounds like you are using different zig versions for linux vs mac.
Are you perhaps using anyzig across two projects initialised at different times? Or are using different computers, that my have different zig versions installed?

What you wrote for linux should work on linux, mac, windows, bsd, any platform zig supports.

I will also point out:

  • GeneralPurposeAllocator is a deprecated alias to the new name DebugAllocator. The old name should have been deleted by the 0.15 release.
  • Init contains a gpa allocator, an arena, and an Io instance among other things. No need to create them yourself. See its docs for more information.
5 Likes

Having different release versions across computers would do it! :man_facepalming: Looks a lot better now, thanks for the help.

pub fn main(init: std.process.Init) !void {
    // Initialise allocator + io
    const allocator: std.mem.Allocator = init.gpa;
    const io: std.Io = init.io;

    // Read Argv for file path
    var args = try init.minimal.args.iterateAllocator(allocator);
    _ = args.skip();
    const path: [:0]const u8 = args.next() orelse return error.MissingArgs;

    // etc
}