Enable exceptions in emscripten with cmake
I’ve been working on a game in cpp recently and one of the things I’ve wanted to try is compiling the game to WASM. The template I started from included an emscripten build, but in my haste to get things done I broke it. This week though I fixed that and can happily report that the web build is up and working.
One issue I ran into is that my cpp build throws exceptions when you want to do something ‘impossible’. Out of the box this isn’t enabled in emscripten, though from playing the game it’s not entirely obvious what’s going on. Every now and again the game was freezing and unresponsive. It wasn’t until I made the connection that it was only freezing when something impossible was happening that I had something to look up. Turns out, when compiling and linking, without the correct flags emscripten won’t enable exceptions. The emscripten docs are here are clear on this. To support the exceptions with my cmake build I added:
target_link_options(${PROJECT_NAME} PRIVATE --preload-file "${CMAKE_CURRENT_SOURCE_DIR}/data@data"
-fexceptions)
target_compile_options(${PROJECT_NAME} PRIVATE -fexceptions)
Note that both compile and linking need the options for it to work.
This forces emscripten to enable the support for throwing and catching exceptions. Once I built with these two flags everything was smooth sailing. Give it a play over here if you like. If you’re having trouble with exceptions in emscripten I hope this helps.