I was recently contacted by someone trying to follow a
previous blog
on cross compiling C to WebAssembly. Things weren’t working; it seemed that things had changed.
This is a short post to look at how to cross compile an open source library to WebAssembly
using the current tooling (as of 2024-01-07).
As before I’ll use the GNU Scientific Library,
which (at the time of writing) is version 2.7.1.
The toolchain
As before I used the clang toolchain from wasi-sdk.
I downloaded wasi-sdk-21.0-linux.tar.gz
and unpacked it to $HOME/local/wasi-sdk-21.0
.
I put the following shell script in the root folder of the GSL.
1 | WASI_SDK_HOME=$HOME/local/wasi-sdk-21.0 |
There are three key changes from the previous method.
First the autoconf
config files in the root folder GSL are overwritten by
those in the was-sdk
with cp $WASI_SDK_HOME/share/misc/config.* .
.
This provides the information autoconf needs to configure the project for
WebAssembly.
Second the flags to the compiler are now --sysroot=$WASI_SDK_HOME/share/wasi-sysroot
,
rather than the previous --target=wasm32-wasi
.
Lastly make
should be called before make install
for the project to build correctly.
Testing
I used the same example program as before.
1 |
|
The following script was used to compile it.
1 | set -x |
The executable was indeed WebAssembly.
1 | $ file example |
As before we can test it with wasmer,
using wasmer-linux-amd64.tar.gz.
version 4.2.5, and unpacked it to $HOME/local/wasmer-4.2.5
.
1 | $ $HOME/local/wasmer-4.2.5/bin/wasmer example |
Success!
Thoughts
It was worth the effort re-visiting this. I think my original
post was incomplete (I suspect I had copied the config files
in the previous attempt and forgotten), but also there were
some real changes.