Chapter 3: C++20/C++23 Discipline on DragonBall m68k

This is an LLM ass-isted document, as are all in the ass/ subdirectory.
Of these, here in the dump/ subdirectory I keep the sloppy & doubtful ones.
I keep these as learning materials for myself, yet to be went thru.

Return to index

1. The Freedom and Peril of Modern C++ on Embedded Retro Hardware

GCC 14 enables developers to write contemporary C++ (classes, templates, concepts, constexpr, user-defined literals, structured bindings, member functions, operator overloading, and RAII). However, running modern C++ on a 16-33 MHz Motorola 68000 DragonBall chip with 128 KB of Dynamic Heap requires strict adherence to embedded architectural constraints.

If you bring desktop C++ assumptions into Palm OS, your application will either fail to link or immediately crash the handheld into a Fatal Exception reboot loop.

2. The Cardinal Rules of Palm OS C++

2.1. Rule 1: Always Declare PilotMain with extern "C"

C++ compilers perform name mangling to encode namespaces and parameter types into symbol names. If you define:

UInt32 PilotMain(UInt16 cmd, void* cmdPBP, UInt16 launchFlags) { ... }

GCC 14 will export the symbol as _Z9PilotMainttPv or _Z9PilotMainv.

Palm OS specifically looks for the un-mangled C symbol PilotMain as the entry vector into code #1. You must guard the entry point with extern "C":

extern "C" {
    UInt32 PilotMain(UInt16 cmd, void* cmdPBP, UInt16 launchFlags);
}

2.2. Rule 2: Mandatory Flags -fno-exceptions and -fno-rtti

Both flags are non-negotiable:

  1. -fno-exceptions:
    • Modern C++ exception handling (throw, try, catch) relies on complex DWARF-2 or SJLJ frame unwinding runtime machinery in libgcc_eh.a and libsupc++.a.
    • Palm OS has no exception unwinding infrastructure.
    • Enabling exceptions inflates the binary code size massively and results in unresolved references at link time (__cxa_throw, __cxa_allocate_exception, etc.).
  2. -fno-rtti:
    • Run-Time Type Information (typeid, dynamic_cast) embeds type name strings and extra vtable pointers into your read-only data.
    • dynamic_cast requires runtime RTTI dispatch routines (__dynamic_cast) from the C++ standard library, which does not exist in our freestanding environment.
    • Compiling with -fno-rtti strips all overhead while preserving full support for virtual methods and polymorphic class hierarchies!

2.3. Rule 3: The Golden Law: Never Use Global or Static Constructors

In a standard desktop environment, the runtime startup routine (__libc_start_main / _init) runs constructors for global objects before main() is invoked.

On Palm OS, this runtime setup does not happen! When the Palm OS launcher executes your app:

  1. It relocates the code and data resources.
  2. It calls PilotMain immediately.
  3. System traps, memory managers, and UI subsystems are only ready inside PilotMain.

If you declare a global object with a constructor:

// DANGEROUS CRASH TRAP!
// This constructor may never run, or run at an undefined time when Palm OS is uninitialized.
MyDatabaseManager gDB("MyAppDB");

extern "C" UInt32 PilotMain(UInt16 cmd, void*, UInt16) {
    gDB.open(); // CRASH or corrupted state!
}

The Fix: Construct all objects on the stack within PilotMain, or use function-local pointers initialized explicitly:

extern "C" UInt32 PilotMain(UInt16 cmd, void*, UInt16) {
    if (cmd != sysAppLaunchCmdNormalLaunch) return 0;

    // Safe: stack constructor runs after Palm OS is fully initialized!
    MyDatabaseManager db("MyAppDB");
    db.open();
    return 0; // destructor runs cleanly before app exit
}

3. What Modern C++ Features Work Out of the Box?

Even with freestanding -fno-exceptions -fno-rtti, an astonishing amount of modern C++ works flawlessly on DragonBall m68k:

Modern C++ Feature Status Notes
Classes & Single/Multiple Inheritance ✅ Works Zero overhead compared to C structs with function pointers
Virtual Functions & vtables ✅ Works 4-byte vtable pointer per object instance; fast indirect call
Templates & Concepts (C++20) ✅ Works Completely resolved at compile-time; zero runtime cost
constexpr & consteval ✅ Works Computed during compilation; drastically saves ROM/RAM footprint
RAII Stack Cleanup ✅ Works Destructors run predictably when stack scopes exit
References & Value Semantics ✅ Works Compiles directly to simple register/pointer indirection
Namespaces ✅ Works Erased during compilation
Standard Casts (static_cast, reinterpret_cast) ✅ Works Checked at compile-time
Custom new / delete ✅ Works When mapped to Palm OS MemPtrNew and MemPtrFree

4. Custom Operators new and delete

Because the host libstdc++ is not available freestanding, if you wish to allocate objects dynamically on the Palm OS Dynamic Heap using new, you must overload global new and delete using Palm OS system calls:

#include <stddef.h>

// Forward declare the Palm OS trap allocator
extern "C" void* MemPtrNew(unsigned long size);
extern "C" short MemPtrFree(void* p);

void* operator new(size_t size) {
    void* ptr = MemPtrNew(size);
    return ptr;
}

void* operator new[](size_t size) {
    return MemPtrNew(size);
}

void operator delete(void* ptr) noexcept {
    if (ptr) MemPtrFree(ptr);
}

void operator delete[](void* ptr) noexcept {
    if (ptr) MemPtrFree(ptr);
}

// Sized delete (C++14 / C++20 requirement)
void operator delete(void* ptr, size_t) noexcept {
    if (ptr) MemPtrFree(ptr);
}

void operator delete[](void* ptr, size_t) noexcept {
    if (ptr) MemPtrFree(ptr);
}

5. RAII Patterns for Palm OS Resources

Resource leaks on Palm OS are catastrophic because the Dynamic Heap is small (e.g., 128 KB) and uncollected memory persists until device reset. Modern C++ RAII (Resource Acquisition Is Initialization) is the best pattern to ensure safety:

// Safe RAII wrapper for a Palm OS Memory Handle
template <typename T>
class LockedRecord {
    void* handle_;
    T* ptr_;
public:
    explicit LockedRecord(void* h) : handle_(h), ptr_(nullptr) {
        if (handle_) {
            ptr_ = static_cast<T*>(MemHandleLock(handle_));
        }
    }

    ~LockedRecord() {
        if (handle_) {
            MemHandleUnlock(handle_);
        }
    }

    // Disable copying to prevent double unlock
    LockedRecord(const LockedRecord&) = delete;
    LockedRecord& operator=(const LockedRecord&) = delete;

    T* get() const { return ptr_; }
    T* operator->() const { return ptr_; }
    T& operator*() const { return *ptr_; }
    explicit operator bool() const { return ptr_ != nullptr; }
};

With this pattern, the record is automatically unlocked even if a function exits early!

6. Further Reading & Reference Resources