Wasm Builders

Cover image for C++ in the web browser using web assembly
gunjan agarwal
gunjan agarwal

Posted on

C++ in the web browser using web assembly

Your project is written in C++, but you want to ship it to the web. Impossible right!!🤔
No, that's definitely possible with web assembly in just simple 3 steps.🥳

  1. Create a web assembly file(.wasm) using your C++ code(.cpp).
  2. Load that file into web browser using JS.
  3. Call a function contained in web assembly from JS code and get the return value.

So, lets get started.
I am using Ubuntu 21.10 (64 bit).


Create web assembly file

Environment Setup
To compile this demo, you must install the following:

  1. C++
  2. Wasmer and Wasienv
  3. Wasmtime

C++ Code Snippet
We will create a Simple C++ Program that will return us the factorial of an Integer Input.
Save it with any file name of your choice, I used Factorial.cpp.

int factorial(int n)
{
  if (n == 0)
    return 1;
  else
    return n * factorial(n-1);
}
Enter fullscreen mode Exit fullscreen mode

Compiling the C++ Code

  1. Compiling Using g++
g++ Factorial.cpp
Enter fullscreen mode Exit fullscreen mode
  1. Compile to WASM Binary
 wasic++ Factorial.cpp -o FactorialBinary.wasm
Enter fullscreen mode Exit fullscreen mode

Hurray🎉 We have our C++ code converted to binary. Now, you just need to load the .wasm file and you can start executing functions from the .wasm file directly using Javascript.
So, lets do it.

Load the file into web browser using JS and calling our factorial function

Create a HTML file and name it Factorial.html

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <script type="module">
      (async() => {
        const response = await fetch('./FactorialBinary.wasm');
        const bytes = await response.arrayBuffer();
        const { instance } = await WebAssembly.instantiate(bytes);
        document.write("<h1>Your factorial is: ", instance.exports.factorial(8), "</h1>");
      })();
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

You can now open Factorial.html in your web browser and your C++ code is shipped on the web.🏁

Result

Happy Coding!! :)

Discussion (2)

Collapse
deepanshu1484 profile image
Deepanshu Arora • Edited on

Hey Gunjan
Great Article

How about extending this to making it work outside the Web Browser using WebAssembly ?

You can take the help of this tutorial, that I have made:
enarx.dev/docs/WebAssembly/C++

Collapse
gunjan_0307 profile image
gunjan agarwal Author • Edited on

Thanks :)
Yeah, that was already there, so I made C++ in web browser.