Convert C/C++ Code to JavaScript Using Emscripten (emsdk)
Do you want to run your high-performance C/C++ code in the browser? Thanks to Emscripten, it's possible to compile C/C++ into WebAssembly (WASM) or JavaScript for seamless integration with web apps
What is Emscripten?
Emscripten is an LLVM-to-WebAssembly compiler that lets you run C/C++ code in browsers by compiling it to WASM or asm.js. It enables near-native speed and brings legacy C/C++ codebases to the web.
In this guide, we’ll:
Create a simple
sum
method in C++Compile it using Emscripten (emsdk)
Integrate it with HTML + JavaScript
See the output in your browser
Prerequisites
Git installed on your system
Python (for Emsdk)
A terminal (Bash or CMD)
A browser (Chrome, Firefox)
Steps:
🌐 Make sure to perform all the steps using same terminal.
Step 1: Install Emscripten (emsdk)
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
emsdk install latest
emsdk activate latest
emsdk_env.bat
Step2: Take any C++ code (for ex: sum.cpp)
#include <emscripten.h>
extern "C" {
EMSCRIPTEN_KEEPALIVE
int sum(int a, int b) {
return a + b;
}
}
INFO: extern "C"
and EMSCRIPTEN_KEEPALIVE
ensure the method is accessible from JS.
Step 3: Compile to WASM
emcc sum.cpp -s WASM=1 -s MODULARIZE=1 -s EXPORT_ES6=1 -s EXPORT_NAME="createModule" -o main.js -std=c++17 --bind -s SINGLE_FILE=1
This generates:
1. sum.js
– JavaScript loader
2. sum.wasm
– WebAssembly binary
Step 4: HTML + JavaScript Integration
Make sure sum.js
, sum.wasm
, and index.html
are in the same directory and served by a local server (like http-server
or Python's http.server
).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Sum in C++ Compiled to WebAssembly</title>
<script src="sum.js"></script>
</head>
<body>
<h1>C++ Sum in WebAssembly</h1>
<p>5 + 7 = <span id="result">...</span></p>
<script>
createModule().then(Module => {
const result = Module._sum(5, 7);
document.getElementById('result').textContent = result;
});
</script>
</body>
</html>
🚀 Run It in the Browser
Start a local server:
python3 -m http.server 8080
You’ll see:
C++ Sum in WebAssembly
5 + 7 = 12
Download Complete Example
You can clone this example from this GitHub repository here
Need help building full projects with C++ + WebAssembly? Drop a comment or reach out!
Thanks.