WebAssembly Tutorial
Selected Reading
- WebAssembly - Discussion
- WebAssembly - Useful Resources
- WebAssembly - Quick Guide
- WebAssembly - Examples
- WebAssembly - Working with Nodejs
- WebAssembly - Working with Go
- WebAssembly - Working with Rust
- WebAssembly - Working with C++
- WebAssembly - Working with C
- WebAssembly - Security
- WebAssembly - Dynamic Linking
- WebAssembly - Convert WAT to WASM
- WebAssembly - Text Format
- WebAssembly - Validation
- WebAssembly - Modules
- WebAssembly - “Hello World”
- WebAssembly - Debugging WASM in Firefox
- WebAssembly - Javascript API
- WebAssembly - Javascript
- WebAssembly - Program Structure
- WebAssembly - Tools to Compile to WASM
- WebAssembly - Installation
- WebAssembly - WASM
- WebAssembly - Introduction
- WebAssembly - Overview
- WebAssembly - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
WebAssembly - Working with C++
WebAssembly - Working with C++
In this chapter, we are going to compile a simple C++ program to javascript and execute the same in the browser.
Example
C++ Program - Reversing a given number.
#include <iostream> int reversenumber(int n) { int reverse=0, rem; while(n!=0) { rem=n%10; reverse=reverse*10+rem; n/=10; } return reverse; }
We have done the installation of emsdk in folder wa/. In same folder, create another folder cprog/ and save above code as reverse.cpp.
We have already installed emsdk in the previous chapter. Here, we are going to make use of emsdk to compile the above c code.
Compile test.c in your command prompt as shown below −
emcc reverse.cpp -s STANDALONE_WASM –o reverse.wasm
emcc command takes care of compipng the code as well as give you the .wasm code.
Example − reversenumber.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>WebAssembly Reverse Number</title> <style> span { font-size : 30px; text-apgn : center; color:orange; } </style> </head> <body> <span id="textcontent"></span> <script> let reverse; fetch("reverse.wasm") .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => {return new WebAssembly.Instance(module) }) .then(instance => { console.log(instance); reverse = instance.exports._Z13reversenumberi(1439898); console.log("The reverse of 1439898 = " +reverse); document.getElementById("textcontent") .innerHTML = "The reverse of 1439898 = " +reverse; }); </script> </body> </html>
Output
The output is as follows −
Advertisements