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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions