Wasm Builders 🧱

Cover image for Wanna build calculator using C and compile it to WebAssembly ?
Shraddha Vijay Inamdar
Shraddha Vijay Inamdar

Posted on • Updated on

Wanna build calculator using C and compile it to WebAssembly ?

In this tutorial, We are going to build a simple calculator using C and compile it to WebAssembly. We will use Wasmer to run outside the browser.

Pre-requisites

Please ensure the steps included in tool setup are completed.

In this example I have used Wasmer as runtime. Please make sure you have installed Wasmer at link.

Writing Code

You can use any IDE of your choice for writing C code.
Here I have used Visual Studio and created one .c file


#include <emscripten.h>

EMSCRIPTEN_KEEPALIVE
float add(float x, float y) {
  return x + y;
}

EMSCRIPTEN_KEEPALIVE
float multiply(float x, float y) {
  return x * y;
}

EMSCRIPTEN_KEEPALIVE
float subtract(float x, float y) {
  return x - y;
}

EMSCRIPTEN_KEEPALIVE
float divide(float x, float y) {
  return x / y;
}

Enter fullscreen mode Exit fullscreen mode

Compile the code using below command :

emcc -O2 -s WASM=1 -s SIDE_MODULE=1 calci.c -o  calci.wasm
Enter fullscreen mode Exit fullscreen mode

Run the code using Wasmer :

wasmer calci.wasm -i add 80 90
Enter fullscreen mode Exit fullscreen mode

Similarly, you can do subtract, divide, multiple.

You can also refer to below picture :

I

Latest comments (1)

Collapse
 
khanon profile image
Lorenzo • Edited

Hello.

Did you use Visual Studio Community or Visual Studio Code? How did you avoid the code errors?
I'm having a hell to be able to configure the IDE with emscripten.

What kind of project did you create to work with WebAssembly?
I'm using a CMake project, but I'm not sure if that's the best option.