How to start using WebAssembly today
.--. .--. ____ .-'''-. ,---. ,---. | |_ | | .' __ `. / _ \| \ / | | _( )_ | |/ ' \ \ (`' )/`--'| , \/ , | |(_ o _) | ||___| / |(_ o _). | |\_ /| | | (_,_) \ | | _.-` | (_,_). '. | _( )_/ | | | |/ \| |.' _ |.---. \ :| (_ o _) | | | ' /\ ` || _( )_ |\ `-' || (_,_) | | | / \ |\ (_ o _) / \ / | | | | `---' `---` '.(_,_).' `-...-' '--' '--'
DISCLAIMER: you should not start using WebAssembly in your projects right now, because the standard is under development and none of the browsers support it. But you can try.
The first thing you need is a browser that supports wasm: you can either use Firefox Nightly or Chrome Canary. Get the browser, then enable WebAssembly support: for Firefox open
about:config and set
true, for Chrome open
chrome://flags/#enable-webassembly and enable the switch. I used Firefox Nightly 50.
Here is how to build it:
First create our
index.html. It can be as simple as this:
And we are going to need our C code:
For building we will need four tools located at:
I will use their basenames because they are in my PATH.
Execute the following commands:
clang -emit-llvm --target=wasm32 -S sample.c llc sample.ll -march=wasm32 s2wasm sample.s > sample.wast sexpr-wasm -o sample.wasm sample.wast
Now you have your C code first compiled to LLVM IR then to wasm through S-expressions representation.
Let’s now take a closer look at each resulting file:
You are now free to delete everything except for
sample.wasm. Start your favorite web-server (I use
busybox httpd -f -p 8000) and point your web browser to it, it should show a button and execute your code each time you click it.