WebAssembly C++ Tutorial
Emscripten also compiles C++ into a WebAssembly module. The same emcc command builds it.
Export add and subtract
KEEPALIVE marks each function for export. The code stays tiny.
#include <emscripten.h>
extern "C" {
EMSCRIPTEN_KEEPALIVE
int add(int a, int b) {
return a + b;
}
EMSCRIPTEN_KEEPALIVE
int subtract(int a, int b) {
return a - b;
}
}Print both answers in C++
A small main prints the sum and the difference. The declarations tell C++ the functions exist.
#include <stdio.h>
extern "C" int add(int, int);
extern "C" int subtract(int, int);
int main() {
printf("%d\n", add(10, 4));
printf("%d\n", subtract(10, 4));
return 0;
}Example
const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAwIAAAcSAgNhZGQAAAhzdWJ0cmFjdAABChECBwAgACABagsHACAAIAFrCw==";
(async () => {
const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
const { instance } = await WebAssembly.instantiate(bytes, {});
console.log("10 + 4 =", instance.exports.add(10, 4));
console.log("10 - 4 =", instance.exports.subtract(10, 4));
})();Key points
- C++ reaches the browser through Emscripten too.
- Use EMSCRIPTEN_KEEPALIVE to keep a function exported.
- Use extern C to stop C++ from renaming the function.
- The demo module below is the same calculator compiled from WAT.
- The calculator adds and subtracts with two small functions.
- C++ turns into a module the browser can run.
In this example, the code decodes the module bytes from B64 and instantiates the module. It calls add with 10 and 4 and logs the sum. Then it calls subtract with 10 and 4 and logs the difference.
Note
the C++ code above needs the Emscripten headers to compile.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does EMSCRIPTEN_KEEPALIVE do?