An Introduction to WebAssembly with C++ — Part I
WebAssembly is a technology that was designed collaboratively for engineers from the major web browsers.
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.
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:
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.
-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.