Build.zig: how to dynamically determine "use_llvm" config

Hey everyone!

With the release 0.14.0, I want to take advantage of the new x86 backend for Linux. My first stab at incorporating it was this:

    const exe = b.addExecutable(.{
        .name = "my-exe",
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
        .link_libc = true,
        .use_llvm = false,
    });

Simple enough. But then, I thought “What if one of my users wanted compile from a machine that wasn’t x86 Linux?

I could add an option to allow the user to set the use_llvm boolean to opt in to the feature, but that feels so manual. My next thought was “How could I use the build system to automatically deduce if my target machine supports use_llvm?

After digging through the code, I found target.query.cpu_arch.?.isX86() to determine the architecture. But I’m stumped on how to find out the OS.

How can I find the OS at build time?

OS is in Target.
The condition is target.result.os.tag == .linux

1 Like

You can check for the OS like this (with target being a std.Build.ResolvedTarget):

target.result.os.tag == .linux

…etc, see: Zig Documentation

BTW… I think instead of target.query you’re supposed to use target.result for such checks (e.g. for the CPU arch: target.result.cpu.arch.isX86()), that way you can also get rid of the .?.

2 Likes

Oops, I forgot share the final state of my solution:

const is_x86_linux = target.result.cpu.arch.isX86() and target.result.os.tag == .linux;
const exe = b.addExecutable(.{
    .name = "my-exe",
    .root_source_file = b.path("src/main.zig"),
    .target = target,
    .optimize = optimize,
    .link_libc = true,
    .use_llvm = !is_x86_linux,
});
1 Like