An Introduction to WebAssembly with C++ — Part I

Camilo Chacón Sartori
2 min readFeb 26, 2018

--

WebAssembly is a technology that was designed collaboratively for engineers from the major web browsers.

In the paper, “Bringing the Web up to Speed with WebAssembly” WebAssembly is defined as a low-level bytecode that is able to compile C/C++ programs to a subset of javascript called asm.js.

WebAssembly opens a range of possibilities actually dominate by Javascript, as mentioned in the paper:

Yet JavaScript has inconsistent performance and a number
of other pitfalls, especially as a compilation target.
WebAssembly addresses the problem of safe, fast, portable
low-level code on the Web.

WebAssembly has three core principles:

  • Safely: Describe a memory-safe sandbox execution environment, also will have the same permissions security policies of the browser.
  • Efficiently: Allow compile C/C++ programs to native machine code for running into a web application.
  • Compact: The code generated using a binary format for reducing load time. Much smaller than a typical javascript file.

Requirement

First, you will install emscripten SDK with the following commands:

$ git clone https://github.com/juj/emsdk.git
$ cd emsdk
$ ./emsdk install latest
$ ./emsdk activate latest

To add the variable environment of Emscripten compiler to your system, type

$ source ./emsdk_env.sh --build=Release

For more installation information: http://webassembly.org/getting-started/developers-guide/

Compiling from C++ Code

For example, the greatest common divisor algorithm in C++ is like this:

GCD Algorithm

Assume that the code above is the file main.cpp and to gcd algorithm have two arguments 190 and 76(the gcd result among both numbers is 38), so going to the terminal, type

$ emcc main.cpp --emrun -s WASM=1 -o test.html

That compiles the main.cpp file to binary format file(.wasm). Description for each flag:

--emrun //This allows use stdout, stderr and exit(return code) into your code, as in the case de std::cout.
-s WASM=1 //Javascript code generation(a js and wasm files).
-o test.html //html page name to generate.

When it is executed:

$ Web server root directory: /…/…/
$ Now listening at http://localhost:8080/

So, open your browser and go to http://localhost:8080/test.html, the result is: 38.

Great! Your first program with WebAssembly.

Update: Thank you to my reddit friends for your comments about the c++ code.

--

--