Search code examples
webassemblyemscripten

Can I compile a forward declaration from C to WebAssembly with Emscripten?


I have C code like this (grossly simplified to illustrate the idea):

#include <stdint.h>
#include <string.h>
#include <stdio.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif

void some_function(int32_t some_argument);

void EMSCRIPTEN_KEEPALIVE my_function(int32_t arg1, int32_t arg2)
{
   some_function(arg1);
   some_function(arg2);
}

I would like to compile this to WebAssembly, with the idea that the forward declaration of some_function gets turned into a WebAssembly import, for the Embedder to provide.

I invoke emscripten with emcc --no-entry -O3 -o mywasm.wasm mycode.c, but it complains that some_function wasn't found: wasm-ld: error: undefined symbol: some_function.

It does make sense because there is no function body - but that's the point: I want that function body to be provided at runtime by the Embedder of the WebAssembly module.

I've checked the documentation for emscripten.h for anything useful, but couldn't find anything that says "make this a required WebAssembly import".

Is there a way to achieve this through emscripten?


Solution

  • Turns out that I needed to pass -s ERROR_ON_UNDEFINED_SYMBOLS=0 to the emcc call.

    The generated wasm will then just have an import for it: (import "env" "some_function" (func $env.some_function (type $t3)))

    Providing that function from the Embedder makes it all work perfectly fine.