Search⌘ K
AI Features

Running Hello World with Emscripten in Node.js

Explore how to compile a simple C program into WebAssembly binary using Emscripten and execute it in a Node.js environment. Learn the process behind the generated binding JavaScript file that facilitates WebAssembly execution and its interactions with Node.js, including memory and stack setup, file handling, and function invocation through ccall and cwrap interfaces.

We'll cover the following...

In this section, we’ll see how to convert C/C++ code into the WebAssembly binary via Emscripten and run it along with Node.js.

Let’s follow the tradition of Brian Kernighan, by writing “Hello, world” with a slight twist. Let’s do a “Hello, Web”:

  1. First, we create a hello_web.c file:

Shell
touch hello_web.c
  1. Launch your favorite editor and add the following code:

C++
#include <stdio.h>
int main() {
printf("Hello, Web!\n");
return 0;
}

It’s a simple C program with a main function. The main function is the entry point during the runtime. When this code is compiled and executed using Clang (clang sum.c && ./a.out), “Hello, Web!” is printed. Now, instead of Clang (or any other compiler), let’s compile the code with emcc.

Shell
emcc hello_web.c
  1. Once completed, the following files are generated:

  • a.out.js

  • a.out.wasm

The generated JavaScript file is huge. It has more than 2,000 lines and is 109 KB in size. We’ll learn how to optimize the file size later.

Let’s run the generated JavaScript file using Node that will print out ...