Compiling C code for Javascript

I was wondering how compilation from C to JavaScript was working using Emscripten. Here are the things I learned from my first experiment.

  • Emscripten comes with a set of functions allowing to transpose APIs like stdlib (printf, fopen) or OpenGL to the browser (and nodejs). This is great. But in my case a lot of useless code was bundled with resulting JS module. I believe it can be removed by tweaking the compiler options.
  • The code is compiled to LLVM bytecode and then converted to ASM.JS. I expect generated code to be efficient.

Here are the files and commands I used for my test.

sum.c

#include <emscripten.h>

int EMSCRIPTEN_KEEPALIVE sum(int a, int b) {
  return a + b;
}

sum.lib.html

<html>
<script src="sum.lib.js"></script>
<script>
console.log(Module._sum(1, 2));
</script>
</html>

Commands:

emcc sum.c -o sum.lib.js

Leave a Reply

Your email address will not be published. Required fields are marked *