I recently showed how to compile a complex C application to WebAssembly using Emscripten. Although effective, this approach comes at the cost of compl

Compiling C to WebAssembly and Running It - without Emscripten

submited by
Style Pass
2022-05-12 15:30:03

I recently showed how to compile a complex C application to WebAssembly using Emscripten. Although effective, this approach comes at the cost of complexity. A lot of JavaScript glue code is produced, and an external tool chain is required. The former obscures the underlying principles, which makes improvement and extension difficult. The latter may not always be possible.

This article shows how to compile C functions to WebAssembly without Emscripten, and then execute the result in a browser. Only a recent LLVM installation is needed. Standard library functions are available with some add-ons.

To my knowledge, the full procedure given in this article has never been described before. It was constructed from various articles describing one or more pieces of what you'll find here. Two articles from earlier this year were especially helpful:

Installation of LLVM on most unix systems should be straightforward. Unfortunately, macOS users may need extra steps. Mojave ships with a partial LLVM toolchain, but it's not complete enough to compile WebAssembly. This problem can be solved by the installation of a full, parallel LLVM suite through Homebrew. Using this approach will preserve Mojave's copy of LLVM for internal use, while allowing you to compile C to WebAssembly when needed.

Leave a Comment