Write your first WebAssembly program

August 8, 2021 ≈ 45 seconds

Today, all the popular modern browsers provide WebAssembly support. But what you can do with it? — With WebAssembly you can run code written in multiple languages, like C, C++, and Rust at near-native speed in the browser!

It's easier to understand with code, so let's write our first WebAssembly program.

#include <emscripten.h>

int EMSCRIPTEN_KEEPALIVE multiply(int x, int y) {
    return x * y;

That's just a function, written in C, which multiplies two numbers. With WebAssembly we can compile it into binary code (.wasm file) and use right from javascript! We would do it with Emscripten compiler.

On macOS, just run

brew install emscripten

Otherwise use this instructions

To compile our C function into .wasm file run

emcc -s hello.c -o hello.wasm --no-entry

Now we can include C function from .wasm file in javascript:

(async function(){
    let { instance } = await WebAssembly.instantiateStreaming(fetch('hello.wasm'));
    console.log(instance.exports.multiply(5, 8)); // 40

Subscribe to our newsletter

If you provide url of your website, we send you free design concept of one element (by our choice)

Subscribing to our newsletter, you comply with subscription terms and Privacy Policy