CMake support

Emscripten ships with a CMake toolchain file that teaches CMake how to cross-compile to WebAssembly with emcc. This page describes how to configure and build CMake projects with Emscripten, and how to write CMakeLists.txt files that work well both for native targets and for Emscripten.

The test/cmake directory in the Emscripten repository contains small CMake projects that are built as part of the Emscripten test suite. They are useful as working examples of the features described on this page.

Configuring and building

Consider a CMake project that you normally build with:

cmake -B build
cmake --build build

To build it with Emscripten, run the configure step through emcmake:

emcmake cmake -B build
cmake --build build

emcmake is only needed for the configure step: it passes the Emscripten toolchain file to CMake, and the generated build files then invoke emcc directly. The build step can be run either with cmake --build, or directly with the build tool of the chosen generator (e.g. make or ninja). emmake is not needed with CMake.

A separate build directory should be for each target platform: a build directory configured for Emscripten can not simultaneously contain a native build, or vice versa. For example:

cmake -B build-native        # A native version will be built here
emcmake cmake -B build-wasm  # An Emscripten compiled version here

To see the exact emcc command lines that CMake runs, build with:

cmake --build build --verbose

What emcmake does

emcmake is a small wrapper over CMake for convenience purposes. The command emcmake cmake [args] runs cmake [args] with the following additions:

  • -DCMAKE_TOOLCHAIN_FILE=<emscripten>/cmake/Modules/Platform/Emscripten.cmake, unless a toolchain file was already given on the command line or in the CMAKE_TOOLCHAIN_FILE environment variable.

  • -DCMAKE_CROSSCOMPILING_EMULATOR=<node>, the Node.js from the Emscripten configuration file, unless an emulator was already given. This lets CMake run the compiled programs (see Running and testing).

  • On Windows, if no generator was given with -G, -G "MinGW Makefiles" is used if mingw32-make is found on the PATH, or else -G Ninja if ninja is found. If neither is found, emcmake exits with an error. The Visual Studio generators can not be used with Emscripten.

Using the toolchain file without emcmake

The toolchain file can also be passed to CMake directly, which is useful e.g. in IDEs or in CMakePresets.json files:

cmake -B build -DCMAKE_TOOLCHAIN_FILE=<emscripten>/cmake/Modules/Platform/Emscripten.cmake

In an emsdk installation, <emscripten> is <emsdk>/upstream/emscripten. For example, a configure preset in CMakePresets.json:

{
  "name": "wasm",
  "binaryDir": "build-wasm",
  "toolchainFile": "$env{EMSDK}/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake"
}

Note that unlike with emcmake, CMAKE_CROSSCOMPILING_EMULATOR is then not passed on the command line. The toolchain file falls back to looking for a node executable on the PATH.

Toolchain options

The following variables can be passed to CMake with -D<VAR>=<value> to customize the toolchain:

EMSCRIPTEN_ROOT_PATH

Path to the Emscripten directory. By default this is detected from the location of the toolchain file, or the EMSCRIPTEN environment variable.

EMSCRIPTEN_FORCE_COMPILERS

ON by default, which skips CMake’s compiler detection and tells CMake directly what the compiler supports, since the detection is slow with Emscripten. Set it to OFF to run CMake’s normal compiler detection.

EMSCRIPTEN_SYSTEM_PROCESSOR

The value of CMAKE_SYSTEM_PROCESSOR. Defaults to x86, since some projects use CMAKE_SYSTEM_PROCESSOR to detect the bitness of the target.

Writing CMakeLists.txt files for Emscripten

Detecting Emscripten

The toolchain file sets the variable EMSCRIPTEN (and also UNIX), and the variable EMSCRIPTEN_VERSION to the version of Emscripten. Use these to maintain a single CMakeLists.txt that builds both natively and with Emscripten:

add_executable(game main.cpp renderer.cpp)

if (EMSCRIPTEN)
  target_sources(game PRIVATE platform_web.cpp)
  target_link_options(game PRIVATE -sALLOW_MEMORY_GROWTH)
else()
  target_sources(game PRIVATE platform_desktop.cpp)
endif()

if (EMSCRIPTEN_VERSION VERSION_LESS 4.0.0)
  message(FATAL_ERROR "Emscripten 4.0.0 or newer is required")
endif()

In C/C++ code, use the __EMSCRIPTEN__ preprocessor define to detect the emcc compiler.

Choosing the output file type

By default, an add_executable() target is linked to a .js file (with a .wasm file on the side). To generate an HTML page instead, set the executable suffix in the CMakeLists.txt file:

set(CMAKE_EXECUTABLE_SUFFIX ".html")

or for a single target:

set_target_properties(game PROPERTIES SUFFIX ".html")

Other suffixes that emcc recognizes, such as .mjs, can be set the same way. See the emcc -o option for the list of output types.

Do not add -o <file> to the compiler or linker flags in order to choose the output file: CMake passes its own -o to every compile and link command, and the two will conflict. To place the output files in a specific directory, use CMAKE_RUNTIME_OUTPUT_DIRECTORY or the RUNTIME_OUTPUT_DIRECTORY target property.

Static libraries (add_library(... STATIC ...)) are built as .a archives that contain Wasm object files. They can be linked into executables as usual.

Compiler and linker flags

Emscripten-specific flags are given with the normal CMake commands. Some flags only affect linking, while others are needed when compiling as well:

  • Link-only flags include most -s settings, e.g. -sEXPORTED_FUNCTIONS, -sMODULARIZE, -sALLOW_MEMORY_GROWTH, and options like --preload-file and --shell-file. Use target_link_options() for these.

  • Flags that change how code is compiled must be passed both when compiling and when linking. These include -pthread, -fwasm-exceptions, -sMEMORY64 (or -m64), and the port options like -sUSE_SDL=2 or --use-port=. Use both target_compile_options() and target_link_options(), or add_compile_options() and add_link_options() to apply them to all targets.

target_compile_options(game PRIVATE -pthread)
target_link_options(game PRIVATE
  -pthread
  -sPTHREAD_POOL_SIZE=4
  -sEXPORTED_FUNCTIONS=_main,_on_resize
  "SHELL:--preload-file ${CMAKE_SOURCE_DIR}/assets@/assets"
)

Write -s settings in the -sNAME=VALUE form without a space after -s. Lists can be given without quotes or brackets, e.g. -sEXPORTED_FUNCTIONS=_main,_foo. For options that take a separate argument, such as --preload-file <path>, use the SHELL: prefix to keep the option and its argument together so that the flag deduplication performed by CMake will not trip up:

target_link_options(game PRIVATE "SHELL:--pre-js ${CMAKE_SOURCE_DIR}/pre.js")

Linking JavaScript files

Emscripten’s toolchain file provides an API for linking JavaScript files into a target. In addition to passing the corresponding emcc flag, they make the target relink when the JavaScript file changes, which does not happen when passing the flags manually with target_link_options():

# Passes --js-library for each file.
em_link_js_library(game library_game.js)
# Passes --pre-js for each file.
em_link_pre_js(game pre.js)
# Passes --post-js for each file.
em_link_post_js(game post.js)

Each function takes the target name, followed by one or more JavaScript files. See Interacting with code for what these files can contain.

Optimization and debug builds

The build type is chosen with CMAKE_BUILD_TYPE as usual:

emcmake cmake -B build -DCMAKE_BUILD_TYPE=Release

The flags of the build type are passed both when compiling and when linking. The default flags are -O3 -DNDEBUG for Release, -Os -DNDEBUG for MinSizeRel, -O2 -g -DNDEBUG for RelWithDebInfo, and -g for Debug.

Finding libraries

Since Emscripten is a cross-compiler, the libraries and headers of the host system can not be used. The toolchain file restricts find_package(), find_library(), find_path() and find_file() to search only in Emscripten’s sysroot (<emscripten cache>/sysroot) and in any paths added to CMAKE_FIND_ROOT_PATH. find_program() still searches the host system, so that host tools like git or python can be found. pkg-config is likewise pointed to the .pc files in the sysroot.

Emscripten ports

Emscripten ports such as SDL2 and SDL3 can be found with find_package(), and linking to them adds the needed -sUSE_* flag to both compiling and linking:

find_package(SDL2 REQUIRED)
target_link_libraries(game SDL2::SDL2)

find_package() also finds the OpenGL, OpenAL and Threads packages, and pkg-config finds the .pc files for e.g. egl, glesv2, glfw3 and sdl.

Configure checks

Configure-time checks like check_include_file(), check_function_exists() and check_type_size() work, and are performed with emcc. Some values that CMake would normally detect, such as type sizes and the byte order (little-endian), are set by the toolchain file directly.

Running and testing

When CMAKE_CROSSCOMPILING_EMULATOR is set (as emcmake does), CMake runs compiled programs with Node.js. This makes add_test() with ctest, try_run(), and custom commands that run a built target work:

enable_testing()
add_test(NAME hello COMMAND hello)

add_custom_command(TARGET hello POST_BUILD
  COMMAND ${CMAKE_CROSSCOMPILING_EMULATOR} $<TARGET_FILE:hello>)

Note that programs that use browser-only features (e.g. WebGL) can not be run this way.

If a project builds a tool that runs on the host during the build (e.g. a code generator), that tool needs a separate native build, since everything in an Emscripten build directory is compiled to WebAssembly. One option is to build the tool with ExternalProject_Add() without the Emscripten toolchain file, or to build it beforehand in a separate native build directory.

Other features and limitations

The Emscripten toolchain file adds support for the following CMake features, which CMake does not provide for the Emscripten platform on its own:

  • Whole archive linking: With CMake 3.24 and newer, the toolchain file defines the WHOLE_ARCHIVE link feature, so target_link_libraries(app $<LINK_LIBRARY:WHOLE_ARCHIVE,mylib>) links all object files from a static library (using -Wl,--whole-archive).

  • Shared libraries: add_library(... SHARED ...) builds side modules for Dynamic Linking. CMake versions 4.2.0 to 4.2.5 and 4.3.0 to 4.3.2 do not support shared libraries with Emscripten (see CMake issue 27240); with these versions the toolchain file disables shared library support and prints a warning.

  • C++ modules: With CMake 3.30 and newer, the toolchain file points CMake to the libc++ standard library modules in the Emscripten sysroot, so import std works when CMAKE_CXX_MODULE_STD is enabled.