Skip to content

Compiling C to WASM

Frequently Used Flags

  • --target=wasm32-unkown-wasi for compiling to wasm
  • -c for compiling as a library without main executable
  • -pthread then the compiler to understand __tls_base etc
  • --sysroot specifying the stand library path

Modify stubs.h

Modify the file stubs.h located in /home/lind-wasm/glibc/target/include/gnu to

/* This file is automatically generated.
   This file selects the right generated file of `__stub_FUNCTION' macros
   based on the architecture being compiled for.  */


//#if !defined __x86_64__
//# include <gnu/stubs-32.h>
//#endif
#if defined __x86_64__ && defined __LP64__
# include <gnu/stubs-64.h>
#endif
#if defined __x86_64__ && defined __ILP32__
# include <gnu/stubs-x32.h>
#endif

After modifying stubs.h remember to run gen_sysroot.sh again

cd /home/lind-wasm/glibc
./gen_sysroot.sh

Then we cd to lind-wasm-tests for testing

cd /home/lind-wasm/lind-wasm-tests

Compile C to wasm

If you don't need to use glibc, modify add.c to the c file you want to compile and add.wasm is the wasm file you get(you can modify add to the name you want). Modify /home/clang+llvm-16.0.4-x86_64-linux-gnu-ubuntu-22.04/bin/clang to you compiler's path

/home/clang+llvm-16.0.4-x86_64-linux-gnu-ubuntu-22.04/bin/clang --target=wasm32 -nostdlib -Wl,--no-entry -Wl,--export-all -o add.wasm add.c

If you need to use glibc(such as printf, printf.c is located in lind-wasm/lind-wasm-tests), modify printf.c to the c file you want to compile and printf.wasm is the wasm file you get(you can modify printf to the name you want). Modify /home/clang+llvm-16.0.4-x86_64-linux-gnu-ubuntu-22.04/bin/clang-16 to you compiler's path

/home/clang+llvm-16.0.4-x86_64-linux-gnu-ubuntu-22.04/bin/clang --target=wasm32-unknown-wasi --sysroot /home/lind-wasm/glibc/sysroot printf.c -g -O0 -o printf.wasm

You should get printf.wasm after compiling printf.c

Run wasmtime

Run the .wasm file, modify the wasmtime path to your own

/home/lind-wasm/wasmtime/target/debug/wasmtime add.wasm

For printf.wasm, you should get Hello World!.