I am not able to call a C function in another JavaScript file, it is giving the error 'called before runtime initialization' please refer to this link

I compiled the C code in emscripten as described in the given link and used generated asm.js file in my test.js file. command used to generate asm :-

emcc test/hello.cpp -o hello.html -s EXPORTED_FUNCTIONS="['_int_sqrt']" -s EXPORTED_RUNTIME_METHODS="["ccall", "cwrap"]"

code in test.js file :

var Module = require('./asm.js');
var test =  Module.cwrap('int_sqrt', 'number', ['number']);
console.log(test(25));

and when I run node test it gives the error

abort(Assertion failed: native function `int_sqrt` called before runtime initialization)
2

There are 2 best solutions below

1
Nour-eddine Taleb On

you should wait for runtime init.
try this:

var Module = require("./lib.js");
var result = Module.onRuntimeInitialized = () => {
    Module.ccall('myFunction', // name of C function 
        null, // return type
        null, // argument types
        null // arguments
   );
}
0
Raydelto Hernandez On

I had the same issue while using emscripten and this has worked for me:

<script>
    Module.onRuntimeInitialized = () => { Module.functionName(param); }
</script>

Where functionName is the name of the function that you want to invoke and param is the value that you want to pass to it.