chapter three

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 the JavaScript plumbing 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 in order to look into three approaches that can be used 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 C and C++ code into asm.js. When work started on the WebAssembly MVP, it was decided that Emscripten would be used because it uses the LLVM compiler and the WebAssembly working group already had experience with LLVM from their 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 rather than asm.js.

3.2   WebAssembly modules

3.2.1   When would you not use a WebAssembly module?

3.3   Emscripten output options

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

3.5   JavaScript plumbing code

3.5.1   Compiling C or C++ with Emscripten generated JavaScript

3.5.2   Creating a basic HTML webpage for use in browsers

3.6   Only the WebAssembly file

3.6.1   Compiling C or C++ as a side module with Emscripten

3.6.2   Loading and instantiating in a browser

3.7   Feature detection: How to test if WebAssembly is available

3.8   Exercises

3.9   Summary