How do I detect the operating system?

Good day!

I’m looking for help with detecting the operating system in Zig. Specifically, I’m trying to replicate the behavior of the following C code:

const char* os_dependent_function() {
#if defined(__FreeBSD__)
    return "string1";
#else
    return "string2";
#endif

}

Thanks in advance.

You have some options:

const builtin = @import("builtin");

// Top level constants are always comptime
const val = if (builtin.target.os.tag == .freebsd) "string1" else "string2";
pub fn func() []const u8 {
    return val;
}

// Or you can assert that an if condition happens at comptime
pub fn func() []const u8 {
    if (comptime builtin.target.os.tag == .freebsd) {
        return "string1";
    } else {
        return "string2";
    }
}
4 Likes

The usingnamespace keyword is useful in situations when you have a large number of functions (or types) that are platform specific:

pub usingnamespace switch (builtin.target.os.tag) {
    .windows => windows_impl,
    else => posix_impl,
};

const posix_impl = struct {
    pub fn osDependentFunction1() void {
          // do stuff in the standard manner
    }

    pub fn osDependentFunction2() void {
          // do stuff in the standard manner
    }
};
const windows_impl = struct {
    pub fn osDependentFunction1() void {
          // do stuff Microsoft's way
    }

    pub fn osDependentFunction2() void {
          // do stuff Microsoft's way
    }
};
1 Like

Please don’t use usingnamespace it might get removed in the near future: Remove `usingnamespace` · Issue #20663 · ziglang/zig · GitHub.

see the link for better alternatives including the usecase discussed here.

1 Like

I don’t agree with the proposal, because it makes the language less ergonomic. The nice thing usingnamespace is that it allows you to quickly collapse a section:

The proposed alternative is definitely not better in this regard.

2 Likes

If the platform specific implementation is getting too big, you can put it in a separate file as I have done here: zig/lib/fuzzer/input_pool.zig at prokop-fuzzer · ProkopRandacek/zig · GitHub