Thursday, January 24, 2019

Compiling C/C++ to WebAssembly (Hello World Guide)

I believe that most C/C++ programmers have heard about web assembly but most of them had trouble on how to getting started. This is a simple guide on how to compile C/C++ into WebAssembly. As usual in programming example, I will start with 'Hello World'.

I hope you like it and let's get started


Environment Specification
I am using Ubuntu 16.04 LTS with standard build tools for C/C++.

$ sudo apt-get install build-essential cmake python git


Compiling the Tools
We need to install toolchain for the firstime for C/C++ language.

git clone https://github.com/juj/emsdk.git

$  cd emsdk
$ ./emsdk install --build=Release sdk-incoming-64bit binaryen-master-64bit
$ ./emsdk activate --build=Release sdk-incoming-64bit binaryen-master-64bit
$ source ./emsdk_env.sh --build=Release
$ echo "source $(pwd)/emsdk_env.sh --build=Release > /dev/null" >> ~/.bashrc


This processes require disk space and take a while for compiling process.

compiling result


Compiling 'Hello World'
Let's start to write code in C/C++ language.(in my case, I will use C++)

$ touch hello.cpp

#include<iostream>
int main() {
  std::cout << "Hello World" << std::endl;
  return 0;
}


Compile it

$ em++ hello.cpp -s WASM=1 -o hello.html

After compiling, it will result hello.html, hello.js and hello.wasm files.
For hello.wasm will contain the compiled code.


Run it

$ emrun hello.html --port 8080

This will start and open browser to see the result

result Hello World



Thank you


Other Topics: