Wasm Builders 🧱

Jennifer
Jennifer

Posted on

ZigLang to WASI

zig

Environment setup

To compile this demo, you must install the following:

Zig

Go to ziglang.org and follow the instructions.

Wasmtime

You will find wasmtime at wasmtime.dev

Zig Code

we would create a simple Zig program that calculates caculates the fibonacci sequence of an integer input.

create a folder with a name of your choice, i would be using "Zig-to-WASI" as the name of my folder.

create a file main.zig, add following code into your main.zig file and save the file.

const std = @import("std");

fn fibonacci(index: u32) u32 {
    if (index < 2) return index;
    return fibonacci(index - 1) + fibonacci(index - 2);
}

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();
    var x: u32 = 7;

    try stdout.print("fibonacci of {d} ", .{x});
    try stdout.print("is: {d} \n ", .{fibonacci(x)}  );
}
Enter fullscreen mode Exit fullscreen mode

Compiling Zig code

Compile using zig

zig run main.zig
Enter fullscreen mode Exit fullscreen mode

compile to WASM using the following command:

zig build-exe main.zig -target wasm32-wasi
Enter fullscreen mode Exit fullscreen mode

The wasm file would be created in same folder

file main.wasm
Enter fullscreen mode Exit fullscreen mode

wasm runtime

wasmtime main.wasm
Enter fullscreen mode Exit fullscreen mode

Top comments (0)