Skip to content

C++ constant string fields are emitted as constexpr std::string, which fails to compile once the value is longer than 15 characters #101

Closed

Description

@matt-edmondson

What's wrong

Two places in Coder/Languages/CppGenerator.cs write constexpr without checking the type:

  • :794 (SpellStorage for FieldDeclaration)
  • :616 (GenerateField for a constant VariableDeclaration)

string maps to std::string (line 48). A constant string field therefore comes out as static constexpr std::string / inline constexpr std::string.

Failure scenario

new FieldDeclaration("Name", "string") {
    IsStatic = true, IsConstant = true,
    InitialValue = Literal.Text("a string longer than fifteen chars") }

Inside a struct this generates:

static constexpr std::string Name = "a string longer than fifteen chars";

g++ 13.3 with -std=c++20 rejects it: "is not a constant expression because it refers to a result of 'operator new'".

Short strings compile only because libstdc++'s small-string buffer holds them. Whether the output builds depends on the literal's length, and it also varies by standard library. Under C++17, constexpr std::string is never valid.

I reproduced this with the built ktsu.Coder.dll and g++ 13.3.

Suggested fix / acceptance criteria

  • For a type that isn't a literal type (at least std::string), write one of:
    • static inline const std::string / inline const std::string
    • std::string_view for the constant: static constexpr std::string_view
  • Add a long-string constant case to CppGeneratedSourceCompilesTests.

Activity

  1. added
    bug
    on Sep 27, 2026
  2. matt-edmondson commented on Sep 27, 2026

    @matt-edmondson
    ContributorAuthor

    Triage

    • Category: Bug
    • Priority: Medium. The generated C++ fails to compile for any constant string longer than the SSO buffer (and for every one under C++17). The failure is loud, not silent, but it depends on the length of the value, so it is easy to miss in tests.
    • Area / suggested assignee: C++ generator, CppGenerator.cs (SpellStorage and the constant path in GenerateField). Owner: @matt-edmondson
    • Duplicates / in progress: no duplicate or open PR. Open PR Write a Rust type's constant fields as associated constants #94 (Rust associated constants) is the same kind of constant-field fix for a different backend, so it may be a useful pattern.
    • Next step: emit static inline const std::string or constexpr std::string_view for non-literal types, and add a long-string case to CppGeneratedSourceCompilesTests.

    Generated by Claude Code

  3. added
    ready
    on Sep 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bugready

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions