ccmakeemscriptenemmake

How to export C function in Emscripten when using CMake


In this tutorial it shows the following example for exporting C functions

./emcc tests/hello_function.cpp -o function.html -s EXPORTED_FUNCTIONS='["_int_sqrt"]' -s EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]'

I would like to do the same except that I use CMake like this

cd bin
emcmake cmake ../src
emmake make

What is the canonical way of specifying -s in emmake? Should I add it to CMakeLists.txt like

set(EXPORTED_FUNCTIONS '["_int_sqrt"]')

or do something similar?


Solution

  • What I figured out so far is that it can be achieved CMake with the following settings

    # Here you can add -s flag during compiling object files
    add_definitions("-s EXPORTED_RUNTIME_METHODS='[\"ccall\",\"cwrap\"]'")
    add_definitions("-s EXTRA_EXPORTED_RUNTIME_METHODS='[\"ccall\",\"cwrap\"]'")
    add_definitions("-s EXPORTED_FUNCTIONS='[\"_testInt\"]'")
    # Here you can add -s flag during linking
    set_target_properties(web_mealy_compiler PROPERTIES LINK_FLAGS "-s EXTRA_EXPORTED_RUNTIME_METHODS=['ccall','cwrap']")
    # Set this if you want to to generate sample html file
    set(CMAKE_EXECUTABLE_SUFFIX ".html")
    

    Then you should be able to call C functions from javascript as follows:

    <script type="text/javascript">
         
        Module['onRuntimeInitialized'] = function() {
         
            console.log("wasm loaded ");
            
            console.log(Module.ccall); // make sure it's not undefined
            console.log(Module._testInt); // make sure it's not undefined
            console.log(Module._testInt()); // this should work
            console.log( Module.ccall('testInt', // name of C function
                'number', // return type
                 [], // argument types
                 []) // argument values
            );
        }
    </script>
    

    And this is my definition of C function:

    #include <emscripten.h>
    EMSCRIPTEN_KEEPALIVE
    int testInt(){
        return 69420;
    }