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

sdgfsdh picture sdgfsdh · Jul 17, 2017 · Viewed 16.9k times · Source

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.

Answer

kazemakase picture kazemakase · Jul 17, 2017

I found this gist to be very helpful.

Basically, this are the steps:

  1. (build llvm and clang 5.0.0 or above with -DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=WebAssembly)
  2. Compile the .cpp soure to llvm bitcode with clang:

    clang -emit-llvm --target=wasm32 -Oz math.cpp -c -o math.bc

  3. Compile the bitcode to s-assembly:

    llc -asm-verbose=false -o math.s math.bc

  4. Use binaryen's s2wasm tool to create a .wast file

    s2wasm math.s > math.wast

  5. Use WABT's wast2wasm tool to translate the textual .wast file into binary .wasm:

    wast2wasm -o math.wasm math.wast

Some of the steps feel redundant but I have not yet found a tool that allows shortcuts. (It would be nice if llc could compile directly to .wasm, or if s2wasm actually created binary .wasm files as the name suggests.) Anyway, once you got the toolchain running it's relatively painless. Note, however, that there are no C or C++ standard libraries for web assembly yet.

Alternatively, if you need the .wasm file just for trying out stuff you can get away without all the toolchain trouble. Browse to https://mbebenita.github.io/WasmExplorer/, paste in your C/C++ code, and download the compiled .wasm file.


Thank you @noontz and @LB-- for pointing out that

Actually as the comments in the gist suggest you can skip binaryen and compile straight to wasm from Clang/LLVM. I'm currently using the following command line for C++ :

clang++ test.cpp -ObjC++ --compile --target=wasm32-unknown-unknown-wasm \ 
        --optimize=3 --output test.wasm