Compiling from C/C++
C and C++ were WebAssembly's first source languages, and they map onto it very directly: int is i32, pointers
are i32 addresses into linear memory, and function pointers are table indices. Two toolchains dominate:
| Toolchain | What you get |
|---|---|
clang with --target=wasm32 |
a bare .wasm file; you provide the imports yourself |
Emscripten (emcc) |
clang + a C library (musl), POSIX emulation, a virtual file system, OpenGL→WebGL, SDL, and generated JS glue |
| wasi-sdk | clang + wasi-libc, for running under WASI runtimes (see WASI) |
A function with bare clang
// sum.c
__attribute__((export_name("sum")))
int sum(const int *values, int count) {
int total = 0;
for (int i = 0; i < count; i++) total += values[i];
return total;
}clang --target=wasm32 -O2 -nostdlib -Wl,--no-entry -o sum.wasm sum.c
wasm2wat sum.wasmThe output is close to this hand-written WAT. Notice how values[i] became a load from values + i * 4, and how the
loop is the block/loop pattern you know:
(module
(import "console" "log" (func $log (param i32)))
(memory (export "memory") 2)
(func $sum (export "sum") (param $values i32) (param $count i32) (result i32)
(local $total i32)
(block $exit
(br_if $exit (i32.lt_s (local.get $count) (i32.const 1))) ;; for loop guard
(loop $body
(local.set $total (i32.add (local.get $total) (i32.load (local.get $values))))
(local.set $values (i32.add (local.get $values) (i32.const 4))) ;; pointer++
(br_if $body (local.tee $count (i32.sub (local.get $count) (i32.const 1))))))
(local.get $total))
;; test: int data[] = {3, 1, 4, 1, 5, 9} placed at address 1024
(data (i32.const 1024) "\03\00\00\00\01\00\00\00\04\00\00\00\01\00\00\00\05\00\00\00\09\00\00\00")
(func (export "main")
(call $log (call $sum (i32.const 1024) (i32.const 6)))
(call $log (call $sum (i32.const 1024) (i32.const 3)))
(call $log (call $sum (i32.const 1024) (i32.const 0)))))23
8
0
The optimiser turned i into a moving pointer and counts count down to zero: a typical -O2 transformation.
The data segment shows how a C array of int is laid out: four little-endian bytes per element.
Where C's memory goes
Clang lays out linear memory like a native process:
0 ─────────── 1024 ──────────── stack top (__stack_pointer starts here, grows down)
(unused) static data: ◄── shadow stack ── heap (malloc) grows up ──►
strings, globalsLocal variables whose address is taken (arrays, structs passed by pointer) live on the shadow stack in linear
memory. The global __stack_pointer tracks it. Here's what a function with a local array compiles to:
int sum_of_squares(int n) { // n <= 8
int squares[8];
for (int i = 0; i < n; i++) squares[i] = i * i;
return sum(squares, n);
}(module
(import "console" "log" (func $log (param i32)))
(memory 2)
(global $__stack_pointer (mut i32) (i32.const 66560))
(func $sum (param $p i32) (param $n i32) (result i32)
(local $t i32)
(block $exit (loop $body
(br_if $exit (i32.eqz (local.get $n)))
(local.set $t (i32.add (local.get $t) (i32.load (local.get $p))))
(local.set $p (i32.add (local.get $p) (i32.const 4)))
(local.set $n (i32.sub (local.get $n) (i32.const 1)))
(br $body)))
(local.get $t))
(func $sum_of_squares (param $n i32) (result i32)
(local $frame i32) (local $i i32) (local $result i32)
;; prologue: reserve 32 bytes (int squares[8])
(local.set $frame (i32.sub (global.get $__stack_pointer) (i32.const 32)))
(global.set $__stack_pointer (local.get $frame))
(block $exit (loop $fill
(br_if $exit (i32.ge_s (local.get $i) (local.get $n)))
(i32.store (i32.add (local.get $frame) (i32.shl (local.get $i) (i32.const 2)))
(i32.mul (local.get $i) (local.get $i)))
(local.set $i (i32.add (local.get $i) (i32.const 1)))
(br $fill)))
(local.set $result (call $sum (local.get $frame) (local.get $n)))
;; epilogue: release the frame
(global.set $__stack_pointer (i32.add (local.get $frame) (i32.const 32)))
(local.get $result))
(func (export "main")
(call $log (call $sum_of_squares (i32.const 5)))
(call $log (call $sum_of_squares (i32.const 8)))
(call $log (global.get $__stack_pointer)))) ;; back to its starting value30
140
66560
Emscripten
Emscripten compiles whole C/C++ programs, including ones that use printf, files, threads and graphics, and
generates the JavaScript glue that provides the system calls:
emcc hello.c -O2 -o hello.html # .wasm + .js glue + a test page
emcc lib.c -O2 -o lib.js \
-sEXPORTED_FUNCTIONS=_sum,_malloc,_free \
-sEXPORTED_RUNTIME_METHODS=ccall,cwrap \
-sMODULARIZE -sEXPORT_ES6 # an ES module you can importimport createModule from './lib.js';
const Module = await createModule();
const sum = Module.cwrap('sum', 'number', ['number', 'number']);
const ptr = Module._malloc(4 * 3);
Module.HEAP32.set([10, 20, 30], ptr / 4); // copy the array into Wasm memory
console.log(sum(ptr, 3)); // 60
Module._free(ptr);printf works because Emscripten's libc implements it on top of an imported fd_write, which its glue forwards
to console.log. Our playground's console.str import plays the same role in miniature.
Calling JavaScript from C
Declare the function in C and let the linker turn it into an import:
__attribute__((import_module("env"), import_name("log_value")))
void log_value(int value);
void report(void) { log_value(42); }Emscripten also offers EM_JS and EM_ASM to write the JavaScript inline in the C source, and Embind for exposing
C++ classes to JS.
Useful flags
| Flag | Effect |
|---|---|
-O2, -O3, -Os, -Oz |
optimise for speed / size |
-g |
DWARF debug info (step through C source in DevTools) |
-msimd128 |
allow SIMD instructions |
-pthread |
threads via Web Workers and shared memory |
-sALLOW_MEMORY_GROWTH |
let malloc grow memory (Emscripten) |
-fwasm-exceptions |
use native Wasm exceptions for C++ throw |
Test yourself
What does a C pointer become in wasm32?
- An externref
- An i32 address into linear memory
- A table index
- A JavaScript object
Where does a C local array like int buf[8] live?
- In Wasm locals
- On the shadow stack in linear memory, managed via
__stack_pointer - In a table
- In a JavaScript array
What does Emscripten add on top of plain clang?
- Nothing
- A C library, POSIX/graphics emulation and generated JS glue
- A garbage collector
- A different instruction set