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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Using emscripten to compile c++ code to javascript for making the sum of two numbers.Practice without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

Answer

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:

EXPORTED_FUNCTIONS='["int_sum_of_two_numbers"]'

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.

We are here to answer your question about Using emscripten to compile c++ code to javascript for making the sum of two numbers.Practice - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji