How to start using WebAssembly today
.--. .--. ____ .-'''-. ,---. ,---. | |_ | | .' __ `. / _ \| \ / | | _( )_ | |/ ' \ \ (`' )/`--'| , \/ , | |(_ o _) | ||___| / |(_ o _). | |\_ /| | | (_,_) \ | | _.-` | (_,_). '. | _( )_/ | | | |/ \| |.' _ |.---. \ :| (_ o _) | | | ' /\ ` || _( )_ |\ `-' || (_,_) | | | / \ |\ (_ o _) / \ / | | | | `---' `---` '.(_,_).' `-...-' '--' '--'
The first thing you need is a browser that supports wasm: support for WebAssembly is enabled by default starting with in Firefox 52 and Chrome 57. If it is not enabled for some reason, for Firefox open
about:config and set
true, for Chrome open
chrome://flags/#enable-webassembly and enable the switch.
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 -o sample.wat wat2wasm sample.wat -o sample.wasm
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.
The easy way
I have recently created a script that automates the building proccess described above. Just clone this repo, then run
./build-all.sh to build the toolchain, then you can pass the filename of your C source code as an argument to
c2wasm script and wasm code will be produced.