Using emscripten to compile c++ code to javascript for making the sum of two numbers.Practice

I want to make a short example to understand how emscripten works. I want to make a html where I could add two numbers in two different text box. I also added a button and a third text box where the result should be printed after I introduce two numbers above and I pressed the button.


I see a few issues with your project. First, I think you should tag the C++ functions with EMSCRIPTEN_KEEPALIVE like this:

int EMSCRIPTEN_KEEPALIVE int_sum_of_two_numbers(int number1, int number2)
    int sum;
    sum = number1 + number2;
    return sum; 

From the Emscripten documentation:

If your function is used in other functions, LLVM may inline it and it will not appear as a unique function in the JavaScript. Prevent inlining by defining the function with EMSCRIPTEN_KEEPALIVE

That allows Javascript code to find your C++ functions.

Besides that, the command you use to compile your project seems to have an extra underscore _ character when you mention the exported functions _int_sum_of_two_numbers => int_sum_of_two_numbers. So you should have used:


As a final note, you could leave the main() function empty. The code inside that function is irrelevant to your web application.

I wrote an article a while ago about integrating WebAssembly with Angular and it is very similar to what you are trying to achieve. I think this would be worth reading.