Generate WebAssembly Modules from C
In this Shortcut, we are going to learn about generating WebAssembly modules from C code. You may have never used C before, but it is still one of the most widely used languages in the world. It has been used extensively since the 1970s as a fast systems programming language with very low overhead compared to a runtime like the Java Virtual Machine. While most developers may not create new code in C today (Rust is increasingly a preferred, safer alternative), there is every likelihood that you may need to bring some C code into a WebAssembly environment.
Unfortunately, there is no opportunity to teach you C here, but there are plenty of good books on the topic in the O’Reilly online catalog. You do not need to have a sophisticated understanding for the discussion at hand.
Let’s begin with some basic C. As is the case in other Shortcuts, the examples will get more sophisticated over time. First we will keep it simple. In the GitHub repository for this Shortcut, you should enter the directory 07-C_Modules
.
The following is a simple C file that calculates the nth Fibonacci number in a sequence. It is called fib.c
in the Shortcut directory:
extern int fib(int n) { int a = 0, b = 1; int c, i; if( n == 0 ) { return a; } for (i = 2; i <= n; i++) { c = a + b; a = b; b = c; } return b; }
The function is clearly intended to be used as a library, because it has been designated with extern
linkage. ...
Get Generate WebAssembly Modules from C now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.