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
- Emscripten SDK installed and configured
- Visual Studio Code (or any code editor)
- A modern browser (e.g., Google Chrome)
1. Create the C Source File
- Open your project folder (e.g.,
WASM
) in Visual Studio Code. - 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:
Filename | Description |
---|---|
hello.html | HTML shell to load and run the WASM module |
hello.js | JavaScript loader and glue code |
hello.wasm | WebAssembly 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
});
}
}
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