How to Compile C++ to WebAssembly

WebAssembly (Wasm) allows developers to run high-performance C++ code directly in the web browser at near-native speed. This guide provides a straightforward, step-by-step walkthrough on how to compile C++ code into a WebAssembly module using the Emscripten toolchain, and how to execute it in a web environment.

1. Install the Emscripten SDK (Emsdk)

Emscripten is the primary toolchain used to compile C and C++ code into WebAssembly.

To install Emscripten, run the following commands in your terminal:

# Clone the Emscripten repository
git clone https://github.com/emscripten-core/emsdk.git

# Enter the repository directory
cd emsdk

# Download and install the latest SDK tools
./emsdk install latest

# Make the "latest" SDK active for the current user
./emsdk activate latest

# Activate environment variables in the current terminal
source ./emsdk_env.sh

(Note: On Windows, use emsdk.bat instead of ./emsdk, and emsdk_env.bat instead of source ./emsdk_env.sh)

2. Write the C++ Code

Create a file named main.cpp. This file contains the C++ code you want to run in the browser. To make functions accessible to JavaScript, wrap them in extern "C" to prevent C++ name mangling, and use the EMSCRIPTEN_KEEPALIVE attribute.

#include <iostream>
#include <emscripten/emscripten.h>

extern "C" {
    // This attribute ensures the function is not optimized away and is exported
    EMSCRIPTEN_KEEPALIVE
    int add(int a, int b) {
        return a + b;
    }
}

int main() {
    std::cout << "WebAssembly module loaded successfully!" << std::endl;
    return 0;
}

3. Compile the Code to WebAssembly

Use the em++ compiler to compile your C++ file. Run the following command in your terminal:

em++ main.cpp -o index.html -s EXPORTED_FUNCTIONS="['_add', '_main']" -s EXPORTED_RUNTIME_METHODS="['ccall', 'cwrap']"

Explanation of the compiler flags:

4. Run the WebAssembly Module

WebAssembly files must be served over a web server due to browser security restrictions (CORS) when loading local files via the file:// protocol.

You can spin up a quick local development server using Python:

# For Python 3
python -m http.server 8080

Open your browser and navigate to http://localhost:8080. You will see the default Emscripten webpage showing the output of the main() function in the console area.

5. Call C++ Functions from JavaScript

To call the add function from the browser’s developer console (F12), use the exported ccall method:

const result = Module.ccall(
    'add',      // C++ function name
    'number',   // Return type
    ['number', 'number'], // Argument types
    [10, 15]    // Arguments
);

console.log(result); // Outputs: 25