Mods in C++
C++ works through the same header as C: surface.h is wrapped in extern "C" for C++, so its calls
are ordinary functions. What C++ does not get is its standard library, because there is no C++
library for a bare wasm32 module. Classes, templates, constexpr and namespaces all work; <string>,
<vector>, exceptions and new do not.
Set up
The same toolchain as C: a clang with the WebAssembly backend, wasm-ld,
and surface.h in the mod's directory. Use clang++.
A mod
"surface.h" { // A string crosses as a pointer and a length. A literal's length is known // at compile time, so this measures it without a C library. Str { char* Data; uint32_t Length; <uint32_t N> constexpr Str( char (&text)[N]) : Data(text), Length(N - 1) {} }; Panel { public: explicit Panel(Str title) { m_Open = axiom_ui_overlay_panel(title.Data, title.Length, &m_Id) == 0; } explicit operator () { m_Open; } Text(Str line) { axiom_ui_overlay_text(m_Id.index, m_Id.generation, line.Data, line.Length); } Graph(Str label, value, uint32_t window) { axiom_ui_overlay_graph(m_Id.index, m_Id.generation, label.Data, label.Length, value, window); } private: AxiomUiOverlayPanelId m_Id{}; m_Open = ; }; } // namespace extern "C" __attribute__((export_name("on_frame"))) OnFrame() { Panel panel{"Hello"}; (!panel) { ; } panel.Text("Drawn by a C++ mod."); panel.Graph("Frame time (ms)", axiom_frame_delta() * 1000.0f, 120); }
Exports the host calls are extern "C", so their names are not mangled, and carry export_name. A
literal's length is known at compile time, so a constructor template measures it without strlen.
Build
-fno-exceptions and -fno-rtti because there is no runtime to support either. Everything else is
as for C.
What to avoid
- Standard headers.
<string_view>,<span>,<array>and the rest are not found forwasm32without a sysroot. Write the small types you need, as theStrabove does. The Axiom repository'ssurface.hpp, with spans andstd::expected, needs a full standard library and is not for mods yet. - Globals with constructors. A mod has no entry point, so
wasm-ldruns static constructors at the start of every export the host calls: a global with a constructor is built again on every frame and every event, and loses its state. Keep globals trivially constructible, orconstexpr, and set them up on the first frame. newanddelete. There is no allocator. Use static storage and fixed arrays.
Events, handles and every capability work exactly as in C: the calls are the same functions.