Exploring WebAssembly (WASM)

Getting Started with WebAssembly

Demo Running a Simple C application in Browser

In this tutorial, you'll learn how to compile and execute a basic C program directly in your browser using WebAssembly. By following these steps, you can seamlessly port native C code to the web.

Prerequisites

1. Create the C Source File

  1. Open your project folder (e.g., WASM) in Visual Studio Code.
  2. Create a file named hello.c with the following content:
#include <stdio.h>

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

2. Compile to WebAssembly

In the integrated terminal, run:

emcc hello.c -o hello.html

This command produces three output files:

FilenameDescription
hello.htmlHTML shell to load and run the WASM module
hello.jsJavaScript loader and glue code
hello.wasmWebAssembly binary containing compiled C code

Verify the files:

ls
# hello.c  hello.html  hello.js  hello.wasm

Note

Ignore any cache:INFO messages during compilation—they’re just Emscripten diagnostics.

3. Run in the Browser

Serve the folder with a static server (for example, Live Server in VS Code) and open hello.html. You should see:

Hello, WebAssembly!

4. Explore the Generated Loader

Open hello.html to inspect how it integrates the loader:

<script>
  Module.setStatus('Downloading...');
  window.onerror = (event) => {
    Module.setStatus('Exception thrown, see JavaScript console');
    spinnerElement.style.display = 'none';
    Module.setStatus = (text) => {
      if (text) console.error('[post-exception status] ' + text);
    };
  };
</script>
<script async type="text/javascript" src="hello.js"></script>

Next, examine the key loader function in hello.js:

function instantiateAsync(binary, binaryFile, imports, callback) {
  if (!binary &&
      typeof WebAssembly.instantiateStreaming === 'function' &&
      isDataUri(binaryFile) &&
      !isFileURI(binaryFile)) {
    return fetch(binaryFile, { credentials: 'same-origin' })
      .then(response => {
        // Handle WebAssembly.instantiateStreaming response
      });
  }
}

The image shows a code editor with JavaScript code open, specifically focusing on WebAssembly (WASM) file handling. The editor displays syntax highlighting and a file explorer on the left.

This snippet demonstrates how the .wasm binary is fetched and instantiated, completing the path from C source to browser execution.

References

Watch Video

Watch video content

Practice Lab

Practice lab

Previous
Demo Setting up the Development Environment