C++ in WebAssembly
C++ support for WebAssembly is handled by the C language support. And C language support is currently excellent.
However, specific C++ tools are maturing quickly. For example, Cheerp targets compiling C++ to WebAssembly with generated JavaScript interop.
Read the C language guide for examples and more coverage of the WASI SDK, Clang, LLVM, and Emscripten
Usage
For the most part, C++ support comes via C support. Both Emscripten and the C WASI SDK provide support for C++. Recent versions of LLVM and Clang support WebAssembly out of the box.
For this reason, it should be possible to compile C++ code both for browser targets and WASI targets. One thing to be aware of with C++, though, is that exception handling is not yet supported.
Pros and Cons
Things we like:
- Because C is so well supported, C++ is among the better supported WebAssembly languages
- It is great that common compilers have added support
- We believe C++-centered tooling for WebAssembly is on the rise
We’re neutral about:
- Setup is not easy, but it is doable
Things we’re not big fans of:
- Features like exception handling are sorely missed
Examples
See the example on the C page.
Learn More
Here are some great resources:
- The WebAssembly and C++ blog post by Evan Martin is a great analysis of the state of C++ dev for WebAssembly.
- Cheerp is an LLVM-based toolchain for compiling C++ to Wasm and JavaScript. An overview blog post explains the basics.
- Mozilla has a tutorial on Compiling C++ to Wasm with Emscripten
- We love this really cool slide presentation with a code walk of C++ in the browser
- Example of building C++ WebAssembly files with Clang
- The yo-wasm tool can help you get started faster. (Yes, we built
yo-wasm
.) - The QT GUI toolkit supports compiling to WebAssembly for the browser. (We blogged about LibreOffice in the browser. That uses QT.)
- An article showing how to use Emscripten to compile C++ to Wasm
- TutorialsPoint has a tutorial for compiling C++ to WebAssembly using Emscripten, but it focuses only on the browser case.