I believe that it should be possible to use zig to compile a simple c library to web assembly.
I am using the following c code
// add.c
int add (int first, int second)
{
return first + second;
}
Once compiled to web assembly I am trying to run it in the browser using the following HTML.
<!DOCTYPE html>
<!-- add.html -->
<html>
<head></head>
<body>
<script type="module">
(async() => {
const response = await fetch('add.wasm');
const bytes = await response.arrayBuffer();
const { instance } = await WebAssembly.instantiate(bytes);
console.log('The answer is: ' + instance.exports.add(1, 2));
})();
</script>
</body>
</html>
To compile the code I have been using a command similar to:
$ zig cc --target=wasm32-freestanding -Wl,--no-entry -Wl,--export-all-symbols -o add.wasm add.c
However when I look at the output in the browser console I get the error message Uncaught (in promise) TypeError: instance.exports.add is not a function. This implies that the function add is being optimised away or not exported.
I have tried adding the -shared and -dynamic switches to the command line and these are not supported for the web assembly target (at least for the version of zig I am using).
Is there a way to ensure that add gets exported?
I serve up the HTML and compiled add.wasm using python -m http.server.
I am using zig 0.15.1. At the time of writing this is the latest release other than the nightly build.