Checking if the build host can run binaries for the target?

Question in title.

Building/packaging a library, I want to (optionally) link the library against a dummy exe and run that exe as part of making sure that the build script works.

I’ve got this in my build script:

// build.zig
// imagine code to build your favourite library here

const test_link = b.option(
    bool,
    "test_link",
    "Test linking the library against a dummy exe",
) orelse false;

if (test_link) {
    const test_module = b.createModule(.{
        .root_source_file = b.path("src/testlink.zig"),
        .target = target,
        .optimize = optimize,
        .link_libc = true,
    });
    test_module.linkLibrary(library);

    const tests = b.addTest(.{
        .root_module = test_module,
    });
    const run_tests = b.addRunArtifact(tests);
    b.getInstallStep().dependOn(&run_tests.step);
}

It works great as long as the host can actually run the test.

Trying to cross compile with the test enabled gets me an error:
"the host system (...) is unable to execute binaries from the target (...)"

The error makes sense, of course, but is there a way for me to check if the build host can run the test suite, so I can gracefully exit with a message about which build option is causing it?

Help is appreciated!

since the build.zig is compiled you can just @import("builtin").target to get the host target info
FYI: -fdarling, -fqemu, -frosetta and -fwine can be used to run artifacts when compiling for other targets

2 Likes

There is also b.graph.host

1 Like

I think I would probably just try to run a binary compiled for the target and skip the tests if it fails to execute.

Trying to figure out ‘correct’ logic for which hosts can run which binaries is more trouble than it’s worth, since it’s not 1:1 with host==target.

(this is also what cmake does, for example)