3

TL;DR

How do I configure CMake and Emscripten to build my static library to produce a WASM and JS bootstrap file?


I have a static library being built with CMake that I want to build as a WASM library (and JS bootstrap) using Emscripten. Simply using the Emscripten CMake toolchain and adding the appropriate compiler/linker flags result in only a .a file being built - even if -o <project name>.js is added to the compiler and/or linker flags.

The reason is that because I've told CMake I want a static library, it uses CMAKE_AR to build. CMAKE_AR (if undefined) is defined as emar in the Emscripten toolchain file, and emar cannot produce .wasm and .js output.

I have tried creating a new executable target that has a dependency on the library, and otherwise just sets up the compiler/linker settings. However this causes a CMake error, because I've defined an executable target that has no source files (they're associated with the library target). If I add a stub main file, I get an Emscripten warning:

system_libs:WARNING: main() is in the input files, but "_main" is not in EXPORTED_FUNCTIONS, which means it may be eliminated as dead code. Export it if you want main() to run.

I could get round by adding an empty file to exe source file list (probably, I haven't tried), but this feels very much like a hack.

cmannett85
  • 21,725
  • 8
  • 76
  • 119

1 Answers1

3

You are correct in that you need to create an executable target in order to produce a .wasm file.

If cmake insists on you creating a dummy source file because it doesn't understand that all the code for your program can come from libraries then I guess you that is your best option.

See CMake: Is it possible to build an executable from only static libraries and no source? for how to work around this limitation of cmake.

sbc100
  • 2,619
  • 14
  • 11
  • This is what I did, thankfully I didn't have to create an empty source file as I could just reference the custom `index.html` I was using to host the WASM library. It feels unsatisfactory as the CMakeLists.txt is quite misleading unless you know the quirks of Emscripten's toolchain - but it works and isolates nicely from the rest of the project. – cmannett85 Aug 28 '20 at 13:27