Wasm32-freestanding in Zig build system

I am trying to build freestanding WASM using the Zig build system.

// build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const wasm_lib = b.addStaticLibrary(.{
        .name = "wasm",
        .root_source_file = b.path("wasm.zig"),
        .target = b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .freestanding }),
        .optimize = .Debug,
    });
    b.installArtifact(wasm_lib);
}
// wasm.zig
export fn identity(a: u32) u32 {
    return a;
}

However, this keeps on building a system-dependent library, not a WASM library:

$ ls zig-out/lib
libwasm.a

How do I make this build a WASM library? Thanks

I should have been using an executable without an entry point. Here is the fixed code:

// build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const wasm_lib = b.addExecutable(.{
        .name = "wasm",
        .root_source_file = b.path("wasm.zig"),
        .target = b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .freestanding }),
        .optimize = .Debug,
    });
    wasm_lib.rdynamic = true;
    wasm_lib.entry = .disabled;
    b.installArtifact(wasm_lib);
}
4 Likes