WebAssembly - Installation


In this chapter, will learn how to install Emscripten SDK to compile C/C++. Emscripten is a Low level virtual machine (LLVM) that takes bytecode generated from C/C++ and compiles it into JavaScript that can easily execute inside the browser.

To compile C/C++ to WebAssembly, we need to first install Emscripten sdk.

Install Emscripten sdk

The steps to install Emscripten sdk are as follows −

Step 1 − Clone the emsdk repo : git clone https://github.com/emscripten-core/emsdk.git.

E:\wa>git clone https://github.com/emscripten-core/emsdk.git 
Cloning into 'emsdk'... 
remote: Enumerating objects: 14, done. 
remote: Counting objects: 100% (14/14), done. 
remote: Compressing objects: 100% (12/12), done. 
remote: Total 1823 (delta 4), reused 4 (delta 2), pack-reused 1809 receiving obje 
cts: 99% (1819/1823), 924.01 KiB | 257.00 KiB/s 
Receiving objects: 100% (1823/1823), 1.01 MiB | 257.00 KiB/s, done. 
Resolving deltas: 100% (1152/1152), done.

Step 2 − Enter inside the directory emsdk.

cd emsdk

Step 3 − For windows: Execute following command.

emsdk install latest

For linux, this command will take some time to install the necessary tools like java, python etc. Follow the below mentioned code −

./emsdk install latest

Step 4 − To activate latest SDK execute following command in your terminal.

For windows, execute the following command −

emsdk activate latest

For linux, execute the below mentioned command −

./emsdk activate latest

Step 5 − To activate PATH and other environment variables run following command in your terminal.

For windows, execute the command −


For linux, execute the following command −

source ./emsdk_env.sh

We are done installing the emsdk and can now compile C or C++ code. The compiling of C/C++ will be done in the next chapters.

To compile any C or C++ code following is the command −

emcc source.c or source.cpp -s WASM=1 -o source.html

The output will give you a source.html file, source.js and source.wasm files. The js will have the api that will fetch the source.wasm and you can see the output, when you hit source.html in the browser.

To just get the wasm file you can use following command. This command will give you only source.wasm file.

emcc source.c or source.cpp -s STANDALONE_WASM