7

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.

1 Answer 1

5

You can explicitly export functions:

zig cc -target wasm32-freestanding -Wl,--no-entry -Wl,--export=add -o add.wasm add.c

(found here)

I don't know why --export-all-symbols doesn't work (the documentation I can find on it says it's for PE targets only, but it does export some additional, internal, symbols to the WASM file).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.