Lesson 5 of 9 · 24m
Compiling C to WebAssembly
Emscripten versus bare Clang, exported functions, memory initialization, filesystem emulation, and how legacy C code becomes a browser-safe compute kernel.
C is why a lot of serious Wasm exists: codecs, compression, SQLite, game engines, image libraries, crypto tooling — decades of mature code that no one sane wants to rewrite in JavaScript. The tradeoff is that C assumes an operating system. Emscripten supplies one; bare Clang does not. Choose consciously.
Emscripten is the practical default
emcc image.c -O3 -o image.js -s EXPORTED_FUNCTIONS='["_resize_rgba","_malloc","_free"]' -s EXPORTED_RUNTIME_METHODS='["ccall","cwrap","HEAPU8"]' -s ALLOW_MEMORY_GROWTH=1 -s MODULARIZE=1 -s EXPORT_ES6=1Emscripten emits both JavaScript glue and Wasm. The glue initializes memory, wires imports, exposes runtime helpers, and can emulate pieces of libc. That's the point — but it also means startup cost and generated code you need to understand.
EXPORTED_FUNCTIONS uses underscore-prefixed C symbol names. If _resize_rgba disappears at runtime, check whether dead-code elimination stripped it because it wasn't exported.
Bare Clang for tiny kernels
If the code doesn't need libc, you can compile closer to the metal:
clang --target=wasm32 -O3 -nostdlib -Wl,--no-entry -Wl,--export=resize_rgba -o kernel.wasm kernel.cThis produces a tiny artifact but pushes memory management and ABI design onto you. Great for embedded codecs and cryptographic kernels; bad for porting a large library that expects fopen.
The filesystem illusion
Emscripten's -s FORCE_FILESYSTEM or preload/embed file features create a virtual filesystem in memory. That's useful for old code, but don't mistake it for persistent browser storage. Files are memory-resident unless you wire persistence explicitly. If the only reason the filesystem exists is to pass one input file, redesign the API as bytes in, bytes out.
Undefined behavior becomes cross-browser behavior
Memory safety bugs in C can produce deterministic-looking corruption inside linear memory. Compile with sanitizers during development where possible, fuzz exposed inputs, and treat fixed offsets and struct layouts as ABI contracts. Wasm doesn't make C safe; it contains some blast radius.
Field notes
_mallocand_freeare part of the ABI when you export them; document ownership rules.ALLOW_MEMORY_GROWTH=1avoids brittle fixed-memory sizing, but growth can invalidate existing typed array views in JavaScript.- Emscripten's generated glue differs substantially between strict modular ES6 output and old script-style output. Don't mix assumptions.
- If a library uses threads, SIMD, or dynamic linking, verify browser and toolchain support before promising the port.
Was this lesson helpful?