Skip to content

Compile C with clang

Erik McClure edited this page Nov 30, 2019 · 2 revisions

There is currently no implementation of the C++ standard library that works on top of webassembly, so if you are trying to compile a webassembly plugin that is platform-independent, you'll need a minimal standard library with at least a malloc replacement. inNative provides you with malloc, realloc, calloc, free, and memcpy via the wasm_malloc.c file that you can compile into your webassembly module as a standard library replacement.

$(CXX) your-code.cpp wasm_malloc.c -g --target=wasm32-unknown-unknown-wasm -nostdlib --optimize=3 -Xlinker --no-entry -Xlinker --export-dynamic

In a makefile, this code will invoke your C++ compiler (probably clang) to create a webassembly module with correctly exported functions and no start function, with a malloc implementation built-in (we've also used -g to embed debug information). Unfortunately, you can't simply have malloc be a webassembly module by itself, because it must declare and manage a linear memory, which makes it non-relocatable. It may be possible to import a linear memory from a module that performs memory allocations, but most C++ compilers don't have the tools to do this. Thus, it is assumed that your program will be a single self-contained webassembly module, for now.

Targeting raw C functions

Because the interfaces proposal has not been merged yet, inNative uses a series of unsupported hacks to add C interop to existing webassembly modules. These hacks are not generated by compilers, and must be done by directly modifying the module using the Schema Editing functions.