}

Webassembly tutorial using emscripten: Hello world example

Created:

Introduction

In our previous tutorial we found a github issue that make us to write a new tutorial.

Alon Zakai (aka kripken) is a researcher at Mozilla and his observations about our tutorial was great and we decided to start a new tutorial.

WebAssembly is a new binary format for the web and a new web standard. It's not limited by javascript.

If you want to know more about webassembly you could read the intro of our previous tutorial, but just the intro!

Emscripten is an open source LLVM-based compiler from C and C++ to JavaScript and int this tutorial will focus on Emscripten.

In this tutorial we are going to write a Hello World example on C and we will use wasm to execute it on the browser that supports webassembly.

The sequence is:

C/C++ => Emscripten+Binaryen => wasm

Installing Emscripten (emcc)

Download the sdk installer for your OS. We are going to use the OSX portable emscripten (emsdk-portable.tar.gz), but it will work the same on Linux and Windows.

For linux and windows execute:

# Fetch the latest registry of available tools.
./emsdk update

# Download and install the latest SDK tools.
./emsdk install latest

# Make the "latest" SDK "active"
./emsdk activate latest

When installation is done, execute or add to your .bashrc:

source ./emsdk_env.sh

C to Webassembly: Hello world example

Open your favorite editor and create a file called hello.c with the following content:

#include <stdio.h>

int main() {
  printf("hello, world!\n");
  return 0;
}

Compile it with:

emcc hello.c -o hello.html -s WASM=1

We use the option -o to generate the html and -s WASM to generate wasm binary file..

This will generate a file called hello.html. You can open this file with a browser with webassembly support. I like to use python to open the files:

# execute this on the hello.html path
python -c 'import SimpleHTTPServer; SimpleHTTPServer.test()'

Now you can go to your browser port 8000.

Webassembly Hello world running on chrome

Conclusion

As you can see emcc will generate the html and wasm file, as opposed to out old tutorial were this files were created manually. This tutorial used a more standard and easy steps to generate a wasm file.