Usage
The basics of using Cheerp
Cheerp is a toolchain that includes executables like clang
(C compiler) and clang++
(C++ compiler) in its bin
directory. We run these executables to compile C and C++ code to JavaScript and WebAssembly.
Hello world
Let’s build a ‘Hello world’ program to see the basics of using Cheerp.
We can compile this with Cheerp by running the following command:
(If this command fails and outputs “file or command not found”, you need to install Cheerp.)
This will produce hello.js
and hello.wasm
files. The JavaScript file will fetch and execute the WebAssembly file.
Using the output
Browser
To run the output in a browser environment, you can include it as a script in an HTML file:
Then open the HTML file in a browser from your filesystem. Notice that this doesn’t work - due to security reasons, hello.js
is not allowed to fetch hello.wasm
when the URL uses the file://
scheme.
Instead, run an HTTP server and open the page there. For example:
You should see “Hello, world!” in the JavaScript console (usually opened with F12
).
This sort of server is fine for development. In production, you will probably be using a web server like nginx, Apache, or similar, which will all work fine.
Node.js
You can run the output directly in a runtime like Node.js:
In CommonJS modules (i.e. not JavaScript modules), you can also require
it from another file:
If you are using JavaScript modules in Node.js, or a runtime that uses them by default like Deno, see below.
Command-line options
Optimisation
To optimise the output, pass a standard optimisation flag like -O3
. Cheerp does not require the use of any post-compilation optimisation tools such as wasmopt.
JavaScript Modules
To output JavaScript modules, use -cheerp-make-module=es6
:
The default export of the module is a function which returns a Promise. The promise resolves when the WebAssembly module has been loaded and its main function has been executed.
You can import it from another module like this:
Other options
Find out more about the available command-line options.
Other examples
You find more examples in the cheerp-meta repository.