Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท Compiling from C, Rust and Others

Compiling C to WebAssembly with Emscripten

Learn how to compile C code to WebAssembly with Emscripten - emcc flags, exported functions, cwrap, malloc and memory, plus runnable examples of what the compiler produces.

Writing WebAssembly by hand is a great way to learn how it works, but nobody ships a product that way. In practice you write C, C++, Rust or another language and let a compiler produce the .wasm file. Emscripten is the oldest and most complete toolchain for C and C++: it wraps the LLVM compiler, a standard library port and a pile of JavaScript glue code into one command, emcc.

This lesson shows the whole path: a C function, the emcc command, the files you get back, and how JavaScript calls the result. The compiler itself cannot run on this site, so the emcc commands are read-only. Every runnable example uses the same kind of .wasm code a compiler would emit, assembled ahead of time, so you can see exactly what the glue code has to deal with.

From C to a .wasm file

Take a small C file. The EMSCRIPTEN_KEEPALIVE macro tells the linker "this function is part of my public API, do not throw it away as dead code".

C
// sum.c
#include <emscripten.h>

EMSCRIPTEN_KEEPALIVE
int sum_to(int n) {
    int total = 0;
    for (int i = 0; i <= n; i++) {
        total += i;
    }
    return total;
}

Compile it with optimization turned on and ask for a standalone .wasm file next to a JavaScript loader:

Terminal
emcc sum.c -O2 -o sum.js
# produces sum.js (loader + glue) and sum.wasm (the module)

If you only want the module and plan to write your own loader, produce a standalone file with no JavaScript at all:

Terminal
emcc sum.c -O2 -o sum.wasm --no-entry

--no-entry means "this is a library, there is no main". Without it, Emscripten expects a main function and wires it up as the program's entry point.

From C to the browser

Write C Plain functions, exported on purpose.
Run emcc LLVM compiles, wasm-ld links.
Get two files A .wasm module and a .js loader.
Load in a page Glue code instantiates and wires imports.

With --no-entry you get only the module.

1 / 2

Exporting functions the right way

There are three common ways to export a C function, and you will meet all of them in real projects.

Method Where Effect
EMSCRIPTEN_KEEPALIVE In the C source Keeps and exports the function
-sEXPORTED_FUNCTIONS=_sum_to,_malloc,_free On the command line Exports by name, with a leading underscore
__attribute__((export_name("sum_to"))) In the C source Clang attribute, no underscore, works without Emscripten too

Notice the leading underscore in EXPORTED_FUNCTIONS: C names get one prepended in Emscripten's naming scheme. If you also want the helper functions cwrap and ccall on the module object, add them with -sEXPORTED_RUNTIME_METHODS=cwrap,ccall.

A quick way to see what a compiled module really exports is the JavaScript API itself. Here is the module a compiler would emit for sum_to, assembled ahead of time. The text-format source is in the comment:

Node.js Inspect what a compiled C module exports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The module has no imports and one export. That is the ideal shape for a pure computation: nothing from the outside world is needed. Real Emscripten output almost always has imports (for printf, abort, time functions), which is why the glue code exists.

Passing numbers: just call it

WebAssembly's native types are i32, i64, f32 and f64. A C int, long (on wasm32), float and double map straight onto them, and JavaScript numbers convert automatically. Pointers are also plain i32 numbers: an address inside linear memory. That is the key fact to remember, because it explains everything about arrays and strings in the next lessons.

With the Emscripten glue, cwrap builds a friendly JavaScript function from a C name and a type description:

JavaScript
// in a page that loaded sum.js (Module is created by the glue)
const sumTo = Module.cwrap('sum_to', 'number', ['number']);
console.log(sumTo(100)); // 5050

Arrays: malloc, write, call, free

C functions that take arrays receive a pointer and a length. JavaScript cannot hand over an array object, so you must copy the data into the module's memory first. Emscripten exports malloc and free for this, and exposes memory views such as HEAP32.

C
// sumarr.c
#include <emscripten.h>
#include <stdint.h>

EMSCRIPTEN_KEEPALIVE
int32_t sum_array(const int32_t *values, int32_t length) {
    int32_t total = 0;
    for (int32_t i = 0; i < length; i++) total += values[i];
    return total;
}
JavaScript
const ptr = Module._malloc(4 * data.length);        // 1. reserve bytes
Module.HEAP32.set(data, ptr >> 2);                  // 2. copy (HEAP32 index = byte address / 4)
const result = Module._sum_array(ptr, data.length); // 3. call
Module._free(ptr);                                  // 4. always release

You can reproduce exactly this dance without Emscripten. The module below exports its memory and a sum_array(ptr, len) function, and we play the role of malloc ourselves by choosing an address:

Node.js malloc, write, call: the manual version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two details matter here. First, a pointer is just a byte offset, so ptr >> 2 converts it to an index in an Int32Array view. Second, a typed array created from memory.buffer goes stale if the memory grows: growth replaces the underlying ArrayBuffer, so you must create a fresh view after any call that might allocate. Emscripten's glue refreshes its HEAP* views for you, and that is one of the quiet services it provides.

Useful emcc flags

Flag What it does
-O0 ... -O3 Speed optimization levels; -O2 is a good default
-Os, -Oz Optimize for size
-g Keep debug info (see Debugging WebAssembly)
-sALLOW_MEMORY_GROWTH=1 Let memory grow instead of failing when malloc runs out
-sINITIAL_MEMORY=64MB Start with a larger heap
-sMODULARIZE -sEXPORT_ES6 Emit the loader as an ES module factory function
-sENVIRONMENT=web,worker Drop code for Node and shells you do not target
-sSTANDALONE_WASM Produce a module that runs without the JS glue (for WASI hosts)

Calling JavaScript from C

Imports go in the other direction. EM_JS defines a JavaScript function that C can call, and EM_ASM runs a snippet inline:

C
#include <emscripten.h>

EM_JS(void, show_total, (int total), {
  document.getElementById('out').textContent = 'Total: ' + total;
});

EMSCRIPTEN_KEEPALIVE
void compute(int n) {
    int total = n * (n + 1) / 2;
    show_total(total);
}

Behind the scenes show_total becomes a wasm import, and the glue code fills it in. You can reimplement this idea in a few lines, which is useful when you build your own loader:

Node.js What EM_JS compiles to: an import

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If you leave out an import the module needs, instantiation fails with a LinkError: the module declared a requirement and the host did not meet it. Emscripten's glue exists largely to meet hundreds of such requirements for you.

Common mistakes

  • Forgetting to export. Without EMSCRIPTEN_KEEPALIVE or EXPORTED_FUNCTIONS, the linker removes your function and Module._name is undefined.
  • C++ name mangling. In C++ files wrap exported functions in extern "C", otherwise the export name is mangled.
  • Leaking memory. Every _malloc needs a matching _free; the garbage collector does not manage linear memory.
  • Stale views. Re-read memory.buffer (or Module.HEAP32) after anything that can grow memory.
  • Assuming a 64-bit long. On wasm32, long is 32 bits. Use int64_t when you need 64, and remember it arrives in JavaScript as a BigInt.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a C pointer when a function is compiled to WebAssembly (wasm32)?

    Linear memory is a flat byte array, so a pointer is simply a byte offset into it. That is why arrays must be copied into memory before being passed.
  2. 2. Why does a C function sometimes vanish from the compiled module?

    Dead-code elimination removes anything unreachable from the entry points. EMSCRIPTEN_KEEPALIVE or EXPORTED_FUNCTIONS marks a function as a root.
  3. 3. What does --no-entry tell emcc?

    Without --no-entry, emcc expects a main function. The flag turns the output into a plain library of exports.
  4. 4. Why must you create a new typed-array view after memory may have grown?

    memory.grow detaches the old ArrayBuffer and creates a larger one. A view built from the old buffer has length 0 afterwards.

Summary

  • Emscripten (emcc) compiles C and C++ to .wasm, optionally with a JavaScript loader.
  • Export functions with EMSCRIPTEN_KEEPALIVE, -sEXPORTED_FUNCTIONS or the Clang export_name attribute.
  • Numbers map directly to i32, i64, f32, f64; pointers are i32 offsets into linear memory.
  • Arrays need malloc, a copy into a heap view, the call, and free.
  • JavaScript functions called from C become wasm imports; missing imports cause a LinkError.
  • -O2, -g, -sALLOW_MEMORY_GROWTH and --no-entry are the flags you will use most.

Next: Compiling Rust with wasm-bindgen