Skip to content

How to use a constant defined in a different header #1873

Description

@Rashmatash

Trying to generate code for two headers:

// Header1.h
static const int MAX_NUMBER = 37;

And

//Header2.h
#include "Header1.h"
static const int someNumber = MAX_NUMBER;

The generated code is

public unsafe partial class Header1
{
  // ... internal stuff
   public const int MAX_NUMBER = 37;
}

public unsafe partial class Header2
{
 // ... internal stuff
   public const int someNumber = MAX_NUMBER; // compile error. Should be Header1.MaxNumber, obviously.
}

How does one go about solving this issue?

Also is it possible to tell CppSharp to only generate data declarations without all the interop/internal code? I just want to convert POD structs and enums from C/C++ to their equivalent in C#.

Activity

  1. tritao commented on Sep 26, 2024

    @tritao
    Collaborator

    The code that handles this is:

    https://github.com/mono/CppSharp/blob/main/src/Generator/Generators/CSharp/CSharpSources.cs#L1627
    https://github.com/mono/CppSharp/blob/main/src/CppParser/Parser.cpp#L3509

    Ideally we would migrate the native parser out of AST::ExpressionObsolete for variable initializers, which has the name suggests is the old obsolete expression representation for expressions, and would use AST::Expr instead via https://github.com/mono/CppSharp/blob/main/src/CppParser/ParseExpr.cpp#L16.

    The easiest fix would be to change the existing code to evaluate this a bit more smartly:
    https://github.com/mono/CppSharp/blob/main/src/CppParser/Parser.cpp#L3820

    I am not sure the exactly code path that is being taken here in that code, but it could be modified to just evaluate this down to 37 directly in the native code, so no reference to Header1 is needed in generation.

    With some of the evaluate functions here: https://clang.llvm.org/doxygen/classclang_1_1Expr.html

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions