Skip to content

Instantly share code, notes, and snippets.

@axic
Created February 10, 2017 01:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save axic/c369b413ae782362f52c6b42bc1e3d7f to your computer and use it in GitHub Desktop.
Save axic/c369b413ae782362f52c6b42bc1e3d7f to your computer and use it in GitHub Desktop.
WebAssembly kickstart guide

WebAssembly kickstart guide

Rolling your own compiler

One of the premises of WebAssembly is to support compiling multiple languages to WebAssembly.

C/C++

Building

Clang has a WebAssembly target, though it is not easy to use currently. First, a custom build must be made.

To build clang:

git clone http://llvm.org/git/llvm.git
cd llvm/tools
git clone http://llvm.org/git/clang.git
cd ../projects
git clone http://llvm.org/git/compiler-rt.git
mkdir ../build
cd ../build
cmake -G Ninja -DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=WebAssembly -DLLVM_TARGETS_TO_BUILD= ..
ninja
cd ../..

Also possible to build using POSIX make:

cmake -G "Unix Makefiles" -DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=WebAssembly -DLLVM_TARGETS_TO_BUILD= ..
make -j 4

This will take anything from 1 to 5 hours.

To build binaryen:

git clone https://github.com/WebAssembly/binaryen.git
cd binaryen
mkdir build
cd build
cmake -G Ninja ..
ninja
cd ../..

Using

Now everything is set to finally compile Hello World!

The compilation process has four steps:

  • compiling (clang)
  • linking to LLVM IR (llc)
  • compiling to WebAssembly S-expressions (s2wasm)
  • compiling to WebAssembly binary (wasm-as)

Note: the last step can also be accomplished with wabt (previously called sexpr-wasm-prototype).

Cheat sheet:

clang -emit-llvm --target=wasm32 -nostdlib -S hello.c
llc -march=wasm32 -o hello.s hello.ll
s2wasm -o hello.wast hello.s
wasm-as -o hello.wasm hello.wast

There you go, you have your very first WebAssembly binary.

@wanderer
Copy link

note: need to install lib32-glibc from multilib on arch

@jakelang
Copy link

--target=wasm32 must be replaced with --target=wasm32-unknown-unknown-elf as the former will cause LLVM to generate __get_global statements, etc that s2wasm does not understand.

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