Compiling C/C++ Module to WebAssembly

When you’ve written a new code module in a language like C/C++, you can compile it into WebAssembly using a tool like Emscripten. Let’s look at how it works.

Emscripten Environment Setup

First, let’s set up the required development environment.

Prerequisites

Get the Emscripten SDK, using these instructions: https://emscripten.org/docs/getting_started/downloads.html

Compiling an example

With the environment set up, let’s look at how to use it to compile a C example to Emscripten. There are a number of options available when compiling with Emscripten, but the main two scenarios we’ll cover are:

  • Compiling to wasm and creating HTML to run our code in, plus all the JavaScript “glue” code needed to run the wasm in the web environment.
  • Compiling to wasm and just creating the JavaScript.

We will look at both below.

Creating HTML and JavaScript

This is the simplest case we’ll look at, whereby you get emscripten to generate everything you need to run your code, as WebAssembly, in the browser.

  1. First we need an example to compile. Take a copy of the following simple C example, and save it in a file called hello.c in a new directory on your local drive:
#include <stdio.h>

int main(int argc, char ** argv) {
    printf("Hello World\n");
}
  1. Now, using the terminal window you used to enter the Emscripten compiler environment, navigate to the same directory as your hello.c file, and run the following command:
emcc hello.c -s WASM=1 -o hello.html

The options we’ve passed in with the command are as follows:

  • -s WASM=1 — Specifies that we want wasm output. If we don’t specify this, Emscripten will just output asm.js, as it does by default.
  • -o hello.html — Specifies that we want Emscripten to generate an HTML page to run our code in (and a filename to use), as well as the wasm module and the JavaScript “glue” code to compile and instantiate the wasm so it can be used in the web environment.

At this point in your source directory you should have:

  • The binary wasm module code (hello.wasm)
  • A JavaScript file containing glue code to translate between the native C functions, and JavaScript/wasm (hello.js)
  • An HTML file to load, compile, and instantiate your wasm code, and display its output in the browser (hello.html)

Running your example

Now all that remains is for you to load the resulting hello.html in a browser that supports WebAssembly. It is enabled by default in Firefox 52+ and Chrome 57+/latest Opera (you can also run wasm code in Firefox 47+ by enabling the javascript.options.wasm flag in about:config, or Chrome (51+) and Opera (38+) by going to chrome://flags and enabling the Experimental WebAssembly flag.)

If everything has worked as planned, you should see “Hello world” output in the Emscripten console appearing on the web page, and your browser’s JavaScript console. Congratulations, you’ve just compiled C to WebAssembly and run it in your browser!

Using a custom HTML template

Sometimes you will want to use a custom HTML template. Let’s look at how we can do this.

  1. First of all, save the following C code in a file called hello2.c, in a new directory:
#include <stdio.h>

int main(int argc, char ** argv) {
    printf("Hello World\n");
}
  1. Search for the file shell_minimal.html in your emsdk repo. Copy it into a sub-directory called html_template inside your previous new directory.

  2. Now navigate into your new directory (again, in your Emscripten compiler environment terminal window), and run the following command:

emcc -o hello2.html hello2.c -O3 -s WASM=1 --shell-file html_template/shell_minimal.html

The options we’ve passed are slightly different this time:

  • We’ve specified -o hello2.html, meaning that the compiler will still output the JavaScript glue code and .html.
  • We’ve also specified --shell-file html_template/shell_minimal.html — this provides the path to the HTML template you want to use to create the HTML you will run your example through.
  1. Now let’s run this example. The above command will have generated hello2.html, which will have much the same content as the template with some glue code added into load the generated wasm, run it, etc. Open it in your browser and you’ll see much the same output as the last example.

Note: You could specify outputting just the JavaScript “glue” file* rather than the full HTML by specifying a .js file instead of an HTML file in the -o flag, e.g. emcc -o hello2.js hello2.c -O3 -s WASM=1. You could then build your custom HTML completely from scratch, although this is an advanced approach; it is usually easier to use the provided HTML template.

  • Emscripten requires a large variety of JavaScript “glue” code to handle memory allocation, memory leaks, and a host of other problems

Calling a custom function defined in C

If you have a function defined in your C code that you want to call as needed from JavaScript, you can do this using the Emscripten ccall() function, and the EMSCRIPTEN_KEEPALIVE declaration (which adds your functions to the exported functions list (see Why do functions in my C/C++ source code vanish when I compile to JavaScript, and/or I get No functions to process?)). Let’s look at how this works.

  1. To start with, save the following code as hello3.c in a new directory:
#include <stdio.h>
#include <emscripten/emscripten.h>

int main(int argc, char ** argv) {
    printf("Hello World\n");
}

#ifdef __cplusplus
extern "C" {
#endif

void EMSCRIPTEN_KEEPALIVE myFunction(int argc, char ** argv) {
    printf("MyFunction Called\n");
}

#ifdef __cplusplus
}
#endif

By default, Emscripten-generated code always just calls the main() function, and other functions are eliminated as dead code. Putting EMSCRIPTEN_KEEPALIVE before a function name stops this from happening. You also need to import the emscripten.h library to use EMSCRIPTEN_KEEPALIVE.

Note: We are including the #ifdef blocks so that if you are trying to include this in C++ code, the example will still work. Due to C versus C++ name mangling rules, this would otherwise break, but here we are setting it so that it treats it as an external C function if you are using C++.

  1. Now add html_template/shell_minimal.html into this new directory too, just for convenience (you’d obviously put this in a central place in your real dev environment).

  2. Now let’s run the compilation step again. From inside your latest directory (and while inside your Emscripten compiler environment terminal window), compile your C code with the following command. (Note that we need to compile with NO_EXIT_RUNTIME, which is necessary as otherwise when main() exits the runtime would be shut down — necessary for proper C emulation, e.g., atexits are called — and it wouldn’t be valid to call compiled code.)

emcc -o hello3.html hello3.c -O3 -s WASM=1 --shell-file html_template/shell_minimal.html -s NO_EXIT_RUNTIME=1  -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall']"
  1. If you load the example in your browser again, you’ll see the same thing as before!

  2. Now we need to run our new myFunction() function from JavaScript. First of all, open up your hello3.html file in a text editor.

  3. Add a <button> element as shown below, just above the first opening <script type='text/javascript'> tag.

<button class="mybutton">Run myFunction</button>
  1. Now add the following code at the end of the first<script> element:
document.querySelector('.mybutton')
    .addEventListener('click', function() {
        alert('check console');
        var result = Module.ccall(
            'myFunction',	// name of C function 
            null,	// return type
            null,	// argument types
            null	// arguments
        );
    });

This illustrates how ccall() is used to call the exported function.

#C+ #cplusplus #WebAssembly

What is GEEK

Buddha Community

Compiling C/C++ Module to WebAssembly

Webassembly for C, Rust, Go, and C#

A 45 minute video presentation that walks through the history of WebAssembly starting with asm.js then demonstrates examples of apps using C, Go, Rust, and C# Blazor.
In this presentation I reviewed:

  • asm.js
  • WebAssembly
  • Building WebAssembly with C using Emscripten
  • How WebAssembly manages memory
  • Creating WebAssembly apps with Go
  • Compiling Rust to WebAssembly
  • Building fullstack apps in C# using Blazor WebAssembly

#c #c# #c++ #programming-c

Tamale  Moses

Tamale Moses

1624240146

How to Run C/C++ in Sublime Text?

C and C++ are the most powerful programming language in the world. Most of the super fast and complex libraries and algorithms are written in C or C++. Most powerful Kernel programs are also written in C. So, there is no way to skip it.

In programming competitions, most programmers prefer to write code in C or C++. Tourist is considered the worlds top programming contestant of all ages who write code in C++.

During programming competitions, programmers prefer to use a lightweight editor to focus on coding and algorithm designing. VimSublime Text, and Notepad++ are the most common editors for us. Apart from the competition, many software developers and professionals love to use Sublime Text just because of its flexibility.

I have discussed the steps we need to complete in this blog post before running a C/C++ code in Sublime Text. We will take the inputs from an input file and print outputs to an output file without using freopen file related functions in C/C++.

#cpp #c #c-programming #sublimetext #c++ #c/c++

Dicey Issues in C/C++

If you are familiar with C/C++then you must have come across some unusual things and if you haven’t, then you are about to. The below codes are checked twice before adding, so feel free to share this article with your friends. The following displays some of the issues:

  1. Using multiple variables in the print function
  2. Comparing Signed integer with unsigned integer
  3. Putting a semicolon at the end of the loop statement
  4. C preprocessor doesn’t need a semicolon
  5. Size of the string matters
  6. Macros and equations aren’t good friends
  7. Never compare Floating data type with double data type
  8. Arrays have a boundary
  9. Character constants are different from string literals
  10. Difference between single(=) and double(==) equal signs.

The below code generates no error since a print function can take any number of inputs but creates a mismatch with the variables. The print function is used to display characters, strings, integers, float, octal, and hexadecimal values onto the output screen. The format specifier is used to display the value of a variable.

  1. %d indicates Integer Format Specifier
  2. %f indicates Float Format Specifier
  3. %c indicates Character Format Specifier
  4. %s indicates String Format Specifier
  5. %u indicates Unsigned Integer Format Specifier
  6. %ld indicates Long Int Format Specifier

Image for post


A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a non-negative integer in the range [0 to 4294967295]. The signed integer is represented in twos-complement notation. In the below code the signed integer will be converted to the maximum unsigned integer then compared with the unsigned integer.

Image for post

#problems-with-c #dicey-issues-in-c #c-programming #c++ #c #cplusplus

Sadie  Ratke

Sadie Ratke

1589830260

Behind the compiler: 20 examples of C# code before and after compiling

Over years I have written many blog posts about C# and .NET that demonstrate also how things work internally and what C# compiler produces from the code we write. I have called these chapters usually as “Behind the compiler”. This post is growing list of my writings covering interesting findings about C# compiler work.

#c# #c #c++ #programming-c

Abdullah  Kozey

Abdullah Kozey

1626250440

Using WebAssembly threads from C, C++ and Rust

WebAssembly threads support is one of the most important performance additions to WebAssembly. It allows you to either run parts of your code in parallel on separate cores, or the same code over independent parts of the input data, scaling it to as many cores as the user has and significantly reducing the overall execution time.

In this article you will learn how to use WebAssembly threads to bring multithreaded applications written in languages like C, C++, and Rust to the web.

How WebAssembly threads work #

WebAssembly threads is not a separate feature, but a combination of several components that allows WebAssembly apps to use traditional multithreading paradigms on the web.

Web Workers #

First component is the regular Workers you know and love from JavaScript. WebAssembly threads use the new Worker constructor to create new underlying threads. Each thread loads a JavaScript glue, and then the main thread uses Worker#postMessage method to share the compiled WebAssembly.Module as well as a shared WebAssembly.Memory (see below) with those other threads. This establishes communication and allows all those threads to run the same WebAssembly code on the same shared memory without going through JavaScript again.

Web Workers have been around for over a decade now, are widely supported, and don’t require any special flags.

SharedArrayBuffer #

WebAssembly memory is represented by a WebAssembly.Memory object in the JavaScript API. By default WebAssembly.Memory is a wrapper around an ArrayBuffer—a raw byte buffer that can be accessed only by a single thread.

> new WebAssembly.Memory({ initial:1, maximum:10 }).buffer
ArrayBuffer { … }

To support multithreading, WebAssembly.Memory gained a shared variant too. When created with a shared flag via the JavaScript API, or by the WebAssembly binary itself, it becomes a wrapper around a SharedArrayBuffer instead. It’s a variation of ArrayBuffer that can be shared with other threads and read or modified simultaneously from either side.

> new WebAssembly.Memory({ initial:1, maximum:10, shared:true }).buffer
SharedArrayBuffer { … }

Unlike postMessage, normally used for communication between main thread and Web Workers, SharedArrayBuffer doesn’t require copying data or even waiting for the event loop to send and receive messages. Instead, any changes are seen by all threads nearly instantly, which makes it a much better compilation target for traditional synchronisation primitives.

SharedArrayBuffer has a complicated history. It was initially shipped in several browsers mid-2017, but had to be disabled in the beginning of 2018 due to discovery of Spectre vulnerabilities. The particular reason was that data extraction in Spectre relies on timing attacks—measuring execution time of a particular piece of code. To make this kind of attack harder, browsers reduced precision of standard timing APIs like Date.now and performance.now. However, shared memory, combined with a simple counter loop running in a separate thread is also a very reliable way to get high-precision timing, and it’s much harder to mitigate without significantly throttling runtime performance.

Instead, Chrome 68 (mid-2018) re-enabled SharedArrayBuffer again by leveraging Site Isolation—a feature that puts different websites into different processes and makes it much more difficult to use side-channel attacks like Spectre. However, this mitigation was still limited only to Chrome desktop, as Site Isolation is a fairly expensive feature, and couldn’t be enabled by default for all sites on low-memory mobile devices nor was it yet implemented by other vendors.

Fast-forward to 2020, Chrome and Firefox both have implementations of Site Isolation, and a standard way for websites to opt-in to the feature with COOP and COEP headers. An opt-in mechanism allows to use Site Isolation even on low-powered devices where enabling it for all the websites would be too expensive. To opt-in, add the following headers to the main document in your server configuration:

Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Opener-Policy: same-origin

Once you opt-in, you get access to SharedArrayBuffer (including WebAssembly.Memory backed by a SharedArrayBuffer), precise timers, memory measurement and other APIs that require an isolated origin for security reasons. Check out the Making your website “cross-origin isolated” using COOP and COEP for more details.

WebAssembly atomics #

While SharedArrayBuffer allows each thread to read and write to the same memory, for correct communication you want to make sure they don’t perform conflicting operations at the same time. For example, it’s possible for one thread to start reading data from a shared address, while another thread is writing to it, so the first thread will now get a corrupted result. This category of bugs is known as race conditions. In order to prevent race conditions, you need to somehow synchronize those accesses. This is where atomic operations come in.

WebAssembly atomics is an extension to the WebAssembly instruction set that allow to read and write small cells of data (usually 32- and 64-bit integers) “atomically”. That is, in a way that guarantees that no two threads are reading or writing to the same cell at the same time, preventing such conflicts at a low level. Additionally, WebAssembly atomics contain two more instruction kinds—“wait” and “notify”—that allow one thread to sleep (“wait”) on a given address in a shared memory until another thread wakes it up via “notify”.

  • All the higher-level synchronisation primitives, including channels, mutexes, and read-write locks build upon those instructions.

#rust #c, c++ #cplusplus #c++ #c #rust programming