WebAssembly Hello World!
Share on:Edit on:
The web is about to get a lot faster by using WebAssembly (wasm). It’s main focus is to convert the code written in C/C++ into webassembly byte code.
This page is a quick guide to install all the packages related to WebAssembly, compile and run a simple Hello World! C program into WebAssembly and to execute that code in browser.
Following are the steps to install necessary tools on Ubuntu Linux distribution.
Installation
Execute following commands in Terminal for git
and cmake
.
$ sudo apt-get install git
$ sudo apt-get install cmake
For Python 2.7.x follow instructions here.
For compiling Emscripten from Source
$ git clone https://github.com/juj/emsdk.git
$ cd emsdk
$ ./emsdk install sdk-incoming-64bit binaryen-master-64bit #This will take a lot time to compile.
$ ./emsdk activate sdk-incoming-64bit binaryen-master-64bit
Execute the following command to enable all Emscripten compiler environmental variables. If new terminal is opened, this command needs to be re-executed.
$ source ./emsdk_env.sh
Compiling Hello World! C program into WebAssembly
Create a directory called hello
.
$ mkdir hello
$ cd hello
Save following C program into hello.c
file.
#include <stdio.h>
int main(int argc, char ** argv)
{
printf("Hello World!");
return 0;
}
Compile above code using Emscripten compiler. To run this program in html page, specify ouput file name with .html
extension (Here it is hello.html
). This html page runs our program in browser.
$ emcc --emrun hello.c -s WASM=1 -o hello.html
Now hello.html
is created. Since WebAssembly is in development state, we need to use latest development versions of Chrome and Firefox. Download either Chrome Canary
or Firefox Nightly
.
This example is tested on Firefox Nightly. To download firefox nightly:
$ sudo apt-get install firefox-trunk
To enable wasm on these browsers, for Chrome: open chrome://flags/#enable-webassembly
in url field and click on enable. For firefox: open about:config
in url field, search for wasm and double click on javascript.options.wasm
to set it to true
. After enabling wasm support Restart
the browser.
This web page, hello.html
can’t be opened directly using browser. Instead a running server is needed to view hello.html
in action. Run following command to run HTTP server.
$ emrun --no_browser --port 8080 .
Now open the web page in your browser by entering following line in url field.
http://localhost:8080/hello.html
You should be seeing Hello World!
on the output console.
