I recently undertook my first WebAssembly project: porting a C video game to the web browser. I plan to record my learnings as a series of Lessons - each covering a major WebAssembly topic. Find Lesson 1 below
What is WebAssembly?
WebAssembly is a new type of code that can be run in modern web browsers. It is a low-level assembly-like language with a compact binary format that runs with near-native performance
What is Emscripten?
Emscripten is a toolchain for compiling to asm.js and WebAssembly. With Emscripten you can:
- Compile C and C++ code into asm.js or WebAssembly
- Do the same for any any other code that can be translated into LLVM bitcode (e.g. D or Rust)
To get started you need the Emscripten SDK
Emscripten is accessed using the Emscripten Compiler Frontend (emcc). This invokes all the other tools needed to build your code. Think of this as a drop-in replacement for a standard compiler like gcc or clang. It is called on the command line using
What is asm.js?
Emscripten takes in C/C++ code, passes it through LLVM, and converts the LLVM-generated bitcode into asm.js
WebAssembly offers all the benefits of asm.js with even faster performance. With more browsers implementing direct support for WebAssembly - and with Emscripten able to output both - asm.js investment is dwindling
First, install and configure the Emscripten SDK. Find instructions here
Next, copy-paste the following C code and save it on your local machine as
At the same folder location, open a shell / command prompt. Invoke the following Emscripten build commands:
You’ll see three new files once the build completes:
hello.wasm- the WebAssembly output
hello.js- the asm.js output
hello.html- a shell / wrapper file so you can launch your WebAssembly app in the browser
For a quick and simple test, run
hello.js with Node JS. It should output “hello, world!”:
Alternatively use lightweight Web Server software such as http-server to serve
hello.html and open it in a Web Browser. It should output “hello, world!” to the Browser window and console:
Congratulations! You’re up and running with WebAssembly!
Next time we’ll look at WebAssembly graphics with SDL