Skip to content

Instantly share code, notes, and snippets.

@elimisteve
Created April 16, 2021 06:11
Show Gist options
  • Save elimisteve/e7aa79a419e6a192bc54a6628ff0d6d8 to your computer and use it in GitHub Desktop.
Save elimisteve/e7aa79a419e6a192bc54a6628ff0d6d8 to your computer and use it in GitHub Desktop.
Compile custom V code to WASM

Compile V Code to WASM

As of 2021.02.11 --

If you don't already have V installed, do so by running

git clone https://github.com/vlang/v
cd v
make
sudo ./v symlink
# Create file cp.v that copies <input_file> to <output_file>
cat > cp.v <<'EOF'
import os

fn main() {
	if os.args.len != 3 {
		eprintln('usage: ${os.base(os.args[0])}.v <input_file> <output_file>')
		exit(1)
	}

	src := os.args[1]
	dest := os.args[2]

	os.cp(src, dest) or {
		eprintln('Error copying input file $src to output file $dest -- $err')
		exit(1)
	}
}
EOF

# Compile cp.v to cp.c
v -o cp.c cp.v

# Install wasienv
curl https://raw.githubusercontent.com/wasienv/wasienv/master/install.sh | sh
source ~/.wasienv/wasienv.sh
cp cp.c cp2.c  # Create backup

wasicc cp.c -o cp.wasm  # Will likely error out
# If so, manually delete the function containing 'WNOHANG', namely
# os__Process_unix_is_alive
${EDITOR:-nano} cp2.c

Once os__Process_unix_is_alive is deleted, save the file then run

wasicc cp2.c -o cp.wasm
echo 'Hello from newly-created copy of hello.txt!' > hello.txt
wasmer --dir=. cp.wasm hello.txt created.txt
cat created.txt

You should now see

Hello from newly-created copy of hello.txt!

on your screen from our WASM program cp.wasm that copied hello.txt to created.txt! 🎉

@elimisteve
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment