Skip to content

michaelfranzl/clang-wasm-browser-starterpack

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Clang-WASM-Browser Starterpack

Minimal working examples of C and C++ software development targeting the web via WebAssembly.

Background

Clang can directly emit WebAssembly since version 8. For simple scenarios, this allows a lean and direct software development workflow targeting the web, omitting more complete SDKs like emscripten.

The wasi-sdk project is a cornerstone in this workflow. It contains no compiler or library code itself; it merely pulls in via git submodules the upstream llvm-project tree, as well as the wasi-libc tree. It contributes a Makefile which compiles these components using suitable flags.

wasi-libc is an implementation of the C standard library which compiles down to WASI syscalls (calls which would 'normally' be done into the OS kernel). The implementation of the actually used syscalls has to be provided (in other words, imported) to the WebAssembly instance. Since we are targeting the web, the implementation is provided by the JavaScript library @wasmer/wasi via the browser.

The wasi-sdk project lacks examples that show how it can be used; the present project aims to fill that gap.

Motivation

Inspired by the awesome emscripten project, I wanted to understand the low-level mechanics of getting compiled C and C++ code to run in the browser, and to find the leanest possible workflow.

Running

Using Nix

nix run
# Wait for it:
# Serving HTTP on 127.0.0.1 port 8000 (http://127.0.0.1:8000/) ...

Manual

Download and extract or install wasi-sdk Release 22.

Set the path to the extracted or installed wasi-sdk as WASI_SDK (default: /opt/wasi-sdk) and run make in the examples subdirectory:

cd examples

WASI_SDK=/path/to/wasi-sdk make

# Start a generic web server:
python3 -m http.server 8000 --bind 127.0.0.1


# In a different terminal:
open http://localhost:8000/

The Examples

The examples start as simple as possible, and then add more and more complexity:

Plain C

C with Standard Library

String handling

Plain C++

C++ with Standard Library