Compile C/C++ into JavaScript with Emscripten and Docker

JavaScript continues its march towards its destiny as the universal programming language, largely due to its cross-platform portability. In previous blog posts, we demonstrated how to cross compile a large, scientific C++ library, ITK, by using cross-compilation capabilities of CMake for a number platforms,

In this post, we will go through the steps to cross-compile ITK to JavaScript and run its test suite. Over a decade of development by hundreds of top-notch research programmers is then immediately accessible to anyone with a web browser.

Edit 2016-10-10: The instructions below now use dockcross. Cross compile for other platforms by replacing dockcross/browser-asmjs with dockcross/linux-armv7, etc.

1) Get the cross-compiling toolchain

As with previous posts, we will use Docker to grab the toolchain:

This Docker image contains of a recent version of CMake and Emscripten, along with Emscripten’s dependencies.

2) Obtain the source and create a build tree

If there is a source tree and build tree, e.g.

3) Build and test

For the purposes of running the test suite, we will add flags for Emscripten that sacrifice run-time performance at the cost of functionality:

Inside the container, the environmental variable CMAKE_TOOLCHAIN_FILE has been configured to point to the toolchain file CMake uses to inform itself about the build environment. Pass this file to CMake during configuration.

The -G Ninja flag tells CMake to use our favorite generator, the Ninja generator.

Emscripten uses NodeJS as the CMAKE_CROSSCOMPILING_EMULATOR; with CMake 3.3 and later, this means NodeJS is used to also run the test suite. For NodeJS to access the file paths passed as command line arguments, the paths must be mounted to the NODEFS file system. ITK’s test driver is instrumented to mount the source tree and build tree when executed.

Start the Experimental dashboard build!

Enjoy ITK!

9 Responses to Compile C/C++ into JavaScript with Emscripten and Docker

  1. Pingback: Jordi Inglada

  2. Pingback: Matt McCormick

  3. Pingback: Matt McCormick

  4. Pingback: Juan Prieto

  5. Pingback: Matt McCormick

  6. Pingback: Juan Prieto

  7. Pingback: Matt McCormick

  8. Pingback: Kevin

    • Pingback: Matt McCormick

Questions or comments are always welcome!