Minimal working examples of C and C++ development targeting the web via WebAssembly.
LLVM/Clang can directly emit WebAssembly since version 8. For simple scenarios, this allows a lean and direct development workflow targeting the web, omitting other SDKs like emscripten.
The wasi-sdk project is a cornerstone in this workflow.
It contains no compiler or library code itself; it merely pulls in via git submodules the upstream
clang tree, as well as the
wasi-libc tree. It contributes a
Makefile which compiles both
projects using suitable flags (most notably disabling pthreads which is not yet supported in
After the building of
wasi-sdk, the entire toolchain (version 12 of
etc.) will be installed in the sub-directory
wasi-sdk project lacks examples that show how it can be used; the present project aims to fill
Inspired by the awesome emscripten project, I wanted to understand the low-level mechanics of getting compiled C and C++ code to run in the browser, and to find the leanest possible workflow.
Instead of writing blog posts and code fragments, I decided to produce working examples, because I believe that working code is king. :)
You only need a modern browser to run the examples, which already contain pre-built WebAssembly code.
The examples start as simple as possible, and then add more and more complexity:
A copy of this repository is hosted on my GitHub Page where these exmples are live.
To run the examples locally, simply serve the example directory using a static file server, e.g. you could use the built-in web server of the Ruby or Python 3 runtime:
cd examples ruby -run -ehttpd . -p8000
cd examples python3 -m http.server 8000
Then visit http://localhost:8000.
Install the dependencies listed below.
# Clone this repository git clone https://github.com/michaelfranzl/clang-wasm-browser-starterpack.git cd lang-wasm-browser-starterpack # Build a specific commit of wasi-sdk git clone --recurse-submodules https://github.com/WebAssembly/wasi-sdk.git # about 1.5 GB cd wasi-sdk git checkout a927856376271224d30c5d7732c00a0b359eaa45 # use llvm 12.0.0 release make cd .. # Build the examples make clean make # Serve the examples locally cd examples ruby -run -ehttpd . -p8000
wasm-optfor WebAssembly code optimization.
wasm-stripto minimize the size of the WebAssembly binary, and
wasm2watto translate binary code to human-readable code.
To provide all these dependencies on Debian 11, simply run:
apt install build-essential binaryen wabt