5 July, 2020

Problem

You’re using Emscripten and would like to detect this in your CMakeLists.txt so that you can something different for Emscripten builds.

Solution

Detect Emscripten with the EMSCRIPTEN variable

Use the EMSCRIPTEN global variable in CMakeLists.txt to detect Emscripten builds.

if (EMSCRIPTEN)
    # Do something Emscripten specific here...
    message(STATUS "This is an Emscripten build.")

    # Set some flags to tell Emscripten that we're using GLFW3, WebGL2, and SDL2_Image.
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s USE_GLFW=3 -s USE_WEBGL2=1")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s USE_SDL_IMAGE=2 -s SDL2_IMAGE_FORMATS=[\"png\"]")
else ()
    # Do something else here...
    message(STATUS "This is NOT an Emscripten build.")
endif ()

This works because the CMake toolchain file, Emscripten.cmake, sets the EMSCRIPTEN global variable as follows:

# Set a global EMSCRIPTEN variable that can be used in client CMakeLists.txt to
# detect when building using Emscripten.
set(EMSCRIPTEN 1 CACHE BOOL "If true, we are targeting Emscripten output.")