枚举初始值设定为常量

时间:2018-03-30 19:32:52

标签: vala

vala枚举是不是基于整数?这个例子生成一个" c"编译错误。没什么大不了的,但想了解原因。

const int INT_UNINITIALIZED = 999;
public enum ScopeTypes {
    /*OSS:Fix:GLib requires a default value, set GLOBALS = 0
     (VSCodeDbgSvr.exe:31979): GLib-GObject-CRITICAL **: g_param_spec_enum: assertion 'g_enum_get_value (enum_class, default_value) != NULL' failed*/
    NONE = INT_UNINITIALIZED,
    GLOBALS = 0,
    ARGUMENTS,
    LOCALS,
    EXCEPTIONS,
    TOT_SCOPE_TYPES;
    //Vala enums may have methods:
    public bool is_global() {
        return (this == GLOBALS || this == EXCEPTIONS);
        }
    public bool is_function() {
        return (this == ARGUMENTS || this == LOCALS);
        }
    public bool is_valid() {
        return (this != NONE);
        }
    }

编译输出:

    > Executing task: /opt/vala/bin/valac helloworld.vala class1.vala --pkg libvala-0.40 -X -I/opt/vala/include/vala-0.40 -X -O0 --vapidir=/opt/vala/share/vala/vapi --debug --save-temps -o helloworld.exe <

   /media/george/SharedData/Projects/Vala/Examples/playground-2/helloworld.c:82:21: error: ‘INT_UNINITIALIZED’ undeclared here (not in a function)
      SCOPE_TYPES_NONE = INT_UNINITIALIZED,
                         ^~~~~~~~~~~~~~~~~
    error: cc exited with status 256
    Compilation failed: 1 error(s), 1 warning(s)
    The terminal process terminated with exit code: 1

1 个答案:

答案 0 :(得分:0)

错误消息的相关部分是:

error: ‘INT_UNINITIALIZED’ undeclared here (not in a function)

C编译器抱怨它无法找到常量的声明。所以它根本不是一个类型问题。

这是范围/订购问题。

如果使用valac -C编译代码,则会得到一个.c文件,如下所示:

typedef enum  {
        SCOPE_TYPES_NONE = INT_UNINITIALIZED,
        SCOPE_TYPES_GLOBALS = 0,
        SCOPE_TYPES_ARGUMENTS,
        SCOPE_TYPES_LOCALS,
        SCOPE_TYPES_EXCEPTIONS,
        SCOPE_TYPES_TOT_SCOPE_TYPES
} ScopeTypes;



#define INT_UNINITIALIZED 999

注意Vala编译器如何重新排序代码以先声明枚举,然后再声明常量。

因为在C中,文件中的声明顺序很重要,所以无法编译。

我认为这是一个编译器错误,您可能希望将此报告给GNOME bugtracker(产品Vala)。