- read

A Hands-On Beginner’s Guide to WebAssembly (WASM)

Traky Deng 30

A Hands-On Beginner’s Guide to WebAssembly (WASM)

Traky Deng
Level Up Coding
Published in
4 min read22 hours ago

--

In this blog, you will be introduced to what WebAssembly is, why it was designed, where it can be run, what applications it has, and follow along a hands-on example to compile C code into WebAssembly and load it with JavaScript to run in browser, without any additional software installation. You will also learn how to inspect the text format of any WASM modules loaded for a web page.

What is WebAssembly?

WebAssembly (or WASM) is a low-level binary format for executing code. It is not a new language meant to be written by hand, but rather, a compilation target for various source languages, such as C, C++, and Rust.

WASM can improve performances of programs as it is executed at near CPU-native speed. See WASM high-level goals for more of its value propositions.

At the time of writing, WebAssembly 1.0 has shipped with 4 major browser engines, which enable WASM support in Chrome, Safari, FireFox, and Microsoft Edge. For more details about browser support, see the roadmap.

Where does WebAssembly run?

WASM code can be run in browser or outside browser in WASM runtimes, as mentioned in a recent CNCF talk on the WASM landscape:

Originally created as a secure sandbox to run compiled C/C++ code in web browsers, WebAssembly (Wasm) has been gaining traction and momentum on the server-side.

The VM in browser, which historically only supported JavaScript, now also supports WASM.

To run WASM code outside of a browser, you can use a standalone WASM runtime, such as Wasmer, Wasmtime, WAVM, or WasmEdge.

See different areas of in-browser and outside-browser use cases identified during the design of WebAssembly.

Example: Compiling a C Program to WASM

In this section, you will be compiling a hello-world C program to WASM and run the code in browser, with the following sample code:

int main() {
printf("Hello, WebAssembly!\n");
return 0;
}

For compilation, you can use an online tool called WasmFiddle, without the requirement of any additional installation. Alternatively, you can choose to download and use Emscripten, a popular toolchain to compile C/C++ to WASM.