WebAssembly – Hello World in Wasm
Now that we have Emscripten installed and ready, let’s create our first Hello World program in WebAssembly using C. We will demonstrate how to compile a simple C program into WebAssembly (.wasm) and run it in the browser.
Writing the Hello World in C
First, we will create a simple program in C that prints “Hello World” to the console. Open your Editor oder IDE and write the following code:
#include
int main() {
printf("Hello, WebAssembly!\n");
return 0;
}
Save this file as hello.c.
Compiling the C Code to WebAssembly
Next we will compile the C code into WebAssembly by using the emcc compiler provided by Emscripten. To convert the .c file into a .wasm module navigate to the directory of your hello.c and run the following command:
emcc hello.c -o hello.html
The -o hello.html tells Emscripten to output an HTML file which will automatically load and run the WebAssembly module in the browser. The hello.html will be generated along with the required .wasm and .js file.
Running the Hello World in the Browser
To run the hello.wasm directly you can open the hello.html file directly. This will open your browser and output “Hello, WebAssembly!” in your browser’s developer console. The browser runs the WebAssembly code via JavaScript, which in turn calls the `printf` function from your C code.
Another possibility is to insert the .wasm in a separate html file. This requires JavaScript code that reads the .wasm file, initializes the module and calls the main function. The HTML file can look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebAssembly Example</title>
</head>
<body>
<h1>Hello World from WebAssembly</h1>
<pre>
<code class="language-javascript">
// Function to load and run the Wasm module
async function loadWasm() {
try {
// Fetch the .wasm file
const wasmFile = await fetch('hello.wasm');
const wasmArrayBuffer = await wasmFile.arrayBuffer();
// Instantiate the WebAssembly module
const wasmModule = await WebAssembly.instantiate(wasmArrayBuffer);
// Call the _main function from the C code
wasmModule.instance.exports._main();
} catch (err) {
console.error('Error loading WebAssembly module', err);
}
}
// Load and execute the WebAssembly module when the script is loaded
loadWasm();
</code>
</pre>
</body>
</html>