Converting C ++ to WebAssembly
Developing a real C++ program that can be executed locally.
You can find many examples on the web that claim to show how to make a wasm application from a C++ source file. But on closer inspection, these are still C source codes. To have here an example of real C++ code, we will add a function which cannot exist in C since it uses the type string to store a string of characters instead of char * in the C language.
Our example of C++ library includes a concat function whose interest is purely demonstrative ...
#include <string>
using namespace std;
int add(int x, int y) {
return x + y;
}
int mul(int x, int y) {
return x * y;
}
float divide(int x, int y) {
if(y == 0) return 0;
return x / y;
}
string concat(string a, string b) {
return a + b;
}
We include the C++ specific string header and the std namespace. This code is saved in the lib.cpp file.
We also create a header in lib.hpp to be able to include this code in a project. Here is its content:
int add(int, int);
int mul(int, int);
float divide(int, int);
string concat(string, string);
Now, an example of application using this C++ library:
/* Demo C++ */
#include <iostream>
#include <string>
using namespace std;
#include "lib.hpp"
int main() {
int a = add(10, 20);
cout << "10 + 20 = " << a << endl;
int m = mul(10, 20);
cout << "10 x 20 = " << m << endl;
float d = divide(30, 10);
cout << "30 / 10 = " << d << endl;
string s = concat("Hello", " World!");
cout << "Concat: " << s << endl;
}
The declaration of the std namespace must precede the inclusion of the arithm.hpp header, because it refers to the type string.
The source is saved in the demo.cpp file.
The wasm application is generated with the following command:
emcc lib.cpp demo.cpp -o demo.wasm
We run the program with this command:
wasmer demo.wasm
This should display the following lines in the console:
10 + 20 = 30
10 x 20 = 200
30 / 10 = 3
Concat: Hello World!
The advantage with a local application run by wasmer or wasmtime is that they know how to include the WASI runtime which contains the standard C++ library.
But if you want to use a wasm library in an HTML application or with node.js, you will have to link WASI yourself to the wasm code and it will be more complicated, which is why a pseudo C++ application which is actually a C code in a C ++ file is insufficient as an example. It should contain code specific to C ++.