🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly C Tutorial: Emscripten Hello World

Emscripten turns C code into a WebAssembly module. Its compiler is called emcc.

Hello in C

C prints with printf. This program prints one line.

#include <stdio.h>

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

Build it with emcc

One command builds the page, the glue, and the module.

emcc hello.c -o hello.html

Add two numbers in C

This add function is the C code emcc compiles.

#include <stdio.h>

int add(int a, int b) {
  return a + b;
}

int main() {
  printf("%d\n", add(2, 3));
  return 0;
}

Example

const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
(async () => {
  const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
  const { instance } = await WebAssembly.instantiate(bytes, {});
  console.log("2 + 3 =", instance.exports.add(2, 3));
  console.log("40 + 2 =", instance.exports.add(40, 2));
})();

Key points

  • Emscripten is a toolchain that compiles C and C++ to WebAssembly.
  • Use emcc to compile a C file into a module.
  • The command emcc hello.c -o hello.html builds a runnable page.
  • Older guides show emcc -s WASM=1, and that flag is on by default now.
  • Learn C first in the C Beginner course on this site.
  • The demo module below is the same add function compiled from WAT.
  • Emscripten turns C into a module the browser can run.

In this example, the code decodes the module bytes from B64 and instantiates the module. It calls add with 2 and 3 and logs the sum. Then it calls add with 40 and 2 and logs that sum.

Note

emcc needs the Emscripten SDK installed before it runs.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does emcc do?