Skip to main content

Build WASM

Build for Browsers

Build WebAssembly from C code using Emscripten.

This is the command to build WebAssembly from C codes for browsers.
This command generates prime.js and prime.wasm. We need both to run on browsers.

build for browsers
emcc src/prime.c -o prime.js -O3 -flto -sWASM=1 -sEXIT_RUNTIME=1 -sINVOKE_RUN=0 -sEXPORTED_FUNCTIONS=_prime -sMODULARIZE=1
build for browsers with more options
emcc src/prime.c -o prime.js -O3 -flto -sWASM=1 -sEXIT_RUNTIME=1 -sINVOKE_RUN=0 -sEXPORTED_FUNCTIONS=_prime,_malloc -sINITIAL_MEMORY=32mb -sALLOW_MEMORY_GROWTH=1 -sMODULARIZE=1
  • -O3 : optimize from the standpoint of speed
  • -flto : enable link time optimization
  • -sWASM=1 : compile targeting wasm
  • -sEXIT_RUNTIME=1 : do not exit wasm at the exit of the function because we want to read the memory of the wasm
  • -sINVOKE_RUN=0 : do not invoke main() function on instantiation
  • -sEXPORTED_FUNCTIONS=_prime,_malloc : make the functions available from javascript
  • -sINITIAL_MEMORY=32mb : enlarge initialmemory size (default is 16 MB)
  • -sMODULARIZE=1 : modularize javascript to enable reuse. if not set, module is initialize globally in the emitted javascript

If optimization options is set to -O3 or higher, function names will be broken. This is not the big problem when using the glue javascript code emitted by compiler.
Other important options like -sEXPORTED_RUNTIME_METHODS=ccall,cwrap or -sINVOKE_RUN=1 can be found at Emscripten Compiler Frontend (emcc).

Build for Standalone

When building the program for standalone runtime, -sSTANDALONE_WASM=1 option is used.
Because main function is not contained, --no-entry option is used here. We need to tell the commands what function should be exported so that we can call them.

The following command generates only prime_standalone.wasm.

build for standalone
emcc src/prime.c -o prime_standalone.wasm -O3 -flto -sWASM=1 -sEXPORTED_FUNCTIONS=_prime -sSTANDALONE_WASM=1 --no-entry

or, when using WAVM runtime

build for standalone WAVM runtime
emcc src/print_prime.c src/prime.c -o print_prime_standalone.wasm -O3 -flto -sWASM=1 -sEXPORTED_FUNCTIONS=_prime,_print_prime -sSTANDALONE_WASM=1 --no-entry
  • --no-entry : this is required when not setting _main in the EXPORTED_FUNCTIONS option