Skip to main content

WebAssembly with C++

C++ WebAssembly

Environment Setup

To compile this demo, you must install the following:


Go to C and C++ Installation and follow the instructions.


Wasmer is an open-source runtime for executing WebAssembly on the Server.


Wasienv is a tool to compile different programming languages to WebAssembly, so you can run your programs on the Browser, or in the Server.


You will find wasmtime at

C++ Code Snippet

We will create a Simple C++ Program that will return us the fibonacci sequence of an Integer Input.

Create a folder "C++-to-WASM":

mkdir C++-to-WASM
cd C++-to-WASM

Create a file named FibonacciSequence.cpp:

// Simple Program to calculate Fibonacci Sequence of an integer input
using namespace std;
int FibonacciSequence(int num) {
if(num <= 1) {
return num ;
return FibonacciSequence(num-1) + FibonacciSequence(num-2);
int main(){
cout << "Enter the Number" << endl;
int n ;
cin >> n ;

cout << "Fibonacci Sequence term at " << n << " " << "is " << FibonacciSequence(n) << endl;

Compiling the C++ Code

  1. Compiling Using g++
g++ FibonacciSequence.cpp

C++ Screenshot1

  1. Compile to WASM Binary using the following Command:

Since the Code has been written in C++, we need to figure out a way to generate a WebAssembly Binary. That's why we will be using wasienv in order to generate a .wasm binary from this cpp file.

When you have your cpp file created, you can execute wasic++

 wasic++ FibonacciSequence.cpp -o FibonacciBinary.wasm

Note that while executing this command, it might generate some warnings but you can ignore them.

  1. Now, you will have a new FibonacciBinary.wasm file ready in your Directory

  2. Executing it using WASM Runtime

wasmtime FibonacciBinary.wasm

C++ Screenshot2