How do I compile a C++ file to WebAssembly?

Viewed 27230

Suppose I have a simple, self-contained C++ file (math.cpp) like this:

int add(int x, int y) {
  return x + y;
}

How would I compile it to WebAssembly (math.wasm)?

Note: I am using the Clang tool-chain.

6 Answers

As of 2019, Clang (8) supports webassembly out of the box. Here is a repository that contains everything needed to compile, link and run a simple .wasm file.

https://github.com/PetterS/clang-wasm

Based on the answers in this thread, I've created a little guide.

For me, the easiest way was to compile emscripten (the website is also a great starting point!) on my machine, compile the code to wasm, generate the appropriate bindings and hide all this in a wrapper on the JS-Side to that I get a nice interface.

Because of the name mangling of c++, I've found getting started with C is easier.

Related