Categories
Web

WebAssembly Kickstart Guide

A quick read about how to start with WebAssembly to have a kick start.

Installation ?

In order to use C, C++ or any other compatible languages in a browser we have to compile it in WebAssembly.

We are going to use the Emscripten tool for this.

Check the instructions given at this page in order to install it (They are fairly simple that’s why not adding in here ?).

Example ?

In this example, I am going to use C language and just do the addition of 2 numbers passed to a C function with JavaScript.

Step 1: Create a C program

create a file named sum.c and add the following lines

int add(int x, int y) {
    return x+y;
}

This is just a simple C function that does addition.

Step 2: Create .wasm file

In order to use this code with JavaScript or say browsers, we have to compile it first.

To compile it run the following command

emcc sum.c -Os -s WASM=1 -s SIDE_MODULE=1 -o sum.wasm

This command will produce a file named sum.wasm

Step 3: Add JavaScript loader

Now we have to load sum.wasm file into JavaScript and have to create 2 textboxes and button to do sum.

Copy code from this gist and add-in sum.html file and open it in the browser.

Live Example ?

https://techio.dev/examples/webassembly/sum.html


Useful stuff

MDN Docs on WebAssembly

MDN Example

The original gist on which the example is based on (I did some alteration)

Side Notes

I started to learn WebAssembly very recently and I am going to keep posting about it.

Emscripten has features to give compiled output with HTML even but I wanted to do it without using the tool as much as possible or say standalone. For that, I had to do a lot of reading over the articles, ran examples given in documents and you know the developer stuff ?.

Leave a Reply

Your email address will not be published. Required fields are marked *