Chapter 3. Creating your first WebAssembly module


This chapter covers

  • An overview of the Emscripten toolkit
  • Creating a module using Emscripten and Emscripten’s HTML template
  • Creating a module with Emscripten JavaScript plumbing code and letting this code handle loading the module
  • Creating a module without the Emscripten JavaScript plumbing code and then loading the module yourself
  • Feature detection to test if WebAssembly is available

In this chapter, you’ll write some C code and then use the Emscripten toolkit to compile it into a WebAssembly module. This will let us look at three approaches we can use with the toolkit to create WebAssembly modules. Just to give you an idea of what’s possible using the toolkit, some of the items that have been ported to WebAssembly using Emscripten include the Unreal Engine 3, SQLite, and AutoCAD.

3.1. The Emscripten toolkit

The Emscripten toolkit is currently the most mature toolkit available to compile C or C++ code into WebAssembly bytecode. It was originally created to transpile such code into asm.js. When work started on the WebAssembly MVP, Emscripten was chosen because it uses the LLVM compiler, and the WebAssembly working group already had experience with LLVM from its work with Google’s Native Client (PNaCl). Emscripten can still be used to transpile C and C++ code into asm.js, but you’ll be using it to compile the code you write into WebAssembly modules.

3.2. WebAssembly modules

3.3. Emscripten output options

3.4. Compiling C or C++ with Emscripten and using the HTML template

3.5. Having Emscripten generate the JavaScript plumbing code

3.6. Having Emscripten generate only the WebAssembly file

3.7. Feature detection: How to test if WebAssembly is available

Real-world use cases