Emscripten is a toolchain that enables C and C++ applications to be compiled into WebAssembly (Wasm), allowing native code to run efficiently inside web browsers. Combined with CMake, which generates platform-specific build configurations from a single project definition, the development workflow becomes structured and portable. CMake can integrate with Emscripten through a custom toolchain file, making it straightforward to configure, build, and manage WebAssembly targets alongside native builds. This tutorial explains how to build program using Emscripten and CMake.
Prepare environment
Before beginning, ensure that the Emscripten SDK and CMake are installed and properly configured on the system.
Build program
- Step 1: Create a new project
Create a directory for the project and move into it:
mkdir test_emsdk && cd test_emsdk
- Step 2: Create CMakeLists.txt file
Create a CMakeLists.txt file inside the project directory:
test_emsdk/CMakeLists.txt
cmake_minimum_required(VERSION 4.2)
project(myapp)
set(CMAKE_CXX_STANDARD 17)
add_executable(${PROJECT_NAME} main.cpp)
This file instructs CMake to generate build files for a simple executable.
- Step 3: Create source file
Create a basic C++ source file:
test_emsdk/main.cpp
#include <iostream>
int main() {
std::cout << "Hello world" << std::endl;
return 0;
}
- Step 4: Create toolchain file
To enable compilation via Emscripten, define a toolchain file:
test_emsdk/emscripten.cmake
set(CMAKE_SYSTEM_NAME Emscripten)
set(CMAKE_C_COMPILER /opt/emsdk/upstream/emscripten/emcc)
set(CMAKE_CXX_COMPILER /opt/emsdk/upstream/emscripten/em++)
This configuration instructs CMake to use Emscripten compilers instead of the system defaults. Note: It is important to adjust the compiler paths so they match the actual installation location of the Emscripten SDK on the system.
- Step 5: Configure the project with CMake
Run CMake to generate build files, specifying the custom toolchain:
cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=emscripten.cmake
Typical output includes compiler detection and build file generation:
-- The C compiler identification is Clang 23.0.0
-- The CXX compiler identification is Clang 23.0.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /opt/emsdk/upstream/emscripten/emcc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /opt/emsdk/upstream/emscripten/em++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (1.6s)
-- Generating done (0.0s)
-- Build files have been written to: /home/ubuntu/myproject/build
- Step 6: Build the project with CMake
Trigger the build process:
cmake --build build
This step compiles the source code into a WebAssembly.
- Step 7: Run the program
Run the compiled program using Node.js:
node build/myapp.js
Leave a Comment
Cancel reply