Wasm: Emscripten vs WASI-SDK
Appearance
WASI-SDK dan Emscripten adalah toolchain untuk compile C/C++ menjadi WebAssembly, tetapi targetnya berbeda:
- WASI-SDK untuk environment WASI (non-web)
- Emscripten untuk browser (web platform).
Emscripten
Cara install
*note: saya pakai Arch Linux
sudo pacman -S emscripten
export PATH="/usr/lib/emscripten/":$PATH
Sekarang buat code C++ simple
// hello.cpp
#include <stdio.h>
int main() {
printf("Hello World\n");
return 0;
}
lalu compile dengan perintah emcc
emcc hello.cpp -o hello.html
Maka secara otomatis emcc akan menghasilkan tiga file yaitu:
- hello.html
- hello.js
- hello.wasm
WASI-SDK
ada beberapa cara install WASI-SDK:
- build manual: tidak disarankan, butuh komputasi berat
- download tar.gz: download dari https://github.com/WebAssembly/wasi-sdk/releases/tag/wasi-sdk-29, ekstrak ke
/optatau ke tempat lain - The Arch Linux Way:
paru -S wasi-sdk-bin
saya pakai cara yang ketiga
Setalah itu install wasmtime, ini adalah runtime untuk menjalankan file .wasm
Ada dua cara:
- cara official:
curl https://wasmtime.dev/install.sh -sSf | bash - The Arch Linux Way:
sudo pacman -S wasmtime
Cara pakai
Masih menggunakan code yang sama
// hello.cpp
#include <stdio.h>
int main() {
printf("Hello World\n");
return 0;
}
Lalu setelah itu:
export WASI_SDK_PATH=/opt/wasi-sdk
$WASI_SDK_PATH/bin/wasm32-wasi-clang++ \
--sysroot=$WASI_SDK_PATH/share/wasi-sysroot \
hello.cpp \
-o hello.wasm
wasmtime hello.wasm