Linux or Mac in Zig

This Zig program demonstrates Zig powerful compile-time metaprogramming by detecting the host operating system at compile time and tailoring its behavior accordingly—without any runtime overhead or unnecessary code in the final binary:

const std = @import("std");
const builtin = @import("builtin");

pub fn main() !void {
    if (builtin.os.tag == .linux) {
        std.debug.print("This is a Linux machine!\n", .{});
    } else if (builtin.os.tag == .macos or builtin.os.tag.isBSD()) {
        std.debug.print("This is a macOS machine!\n", .{});
    } else {
        @compileError("Unsupported operating system");
    }
}

The program starts by importing the standard library (std) for printing and the builtin package, which exposes compile-time constants about the target platform. Inside the main() function (which returns !void to allow error handling), a series of if/else if conditions inspect the value of builtin.os.tag, a comptime-known enum. If the program is being compiled for Linux, it simply prints “This is a Linux machine!”. For macOS or any BSD variant (via the handy .isBSD() method), it prints “This is a macOS machine!”. On any other operating system, the @compileError() statement immediately halts compilation with a clear message, preventing the code from ever building on unsupported platforms.

Because builtin.os.tag is evaluated entirely at compile time, Zig optimizer eliminates all dead branches. The resulting executable contains only the single std.debug.print() call that matches the target OS—making the program tiny, fast, and perfectly tailored.

Save this as linuxMac.zig and execute it as follows:

$ zig version
0.15.2
$ zig run linuxMac.zig
This is a macOS machine!

Happy coding in Zig!