【问题标题】:Why am I getting a compilation warning when converting a unichar to a string in vala?为什么在 vala 中将 unichar 转换为字符串时会收到编译警告?
【发布时间】:2012-05-19 15:18:31
【问题描述】:

这是一个演示该问题的简短程序:

void main(string[] args)
{
    unichar c = 'a';
    string str_from_to_string = c.to_string(); // Warning
    stdout.printf("Converted by unichar.to_string: \"%s\"\n", str_from_to_string);
}

这也会导致同样的警告:

void main(string[] args)
{
    unichar c = 'a';
    string str_from_template = @"$c"; // Warning
    stdout.printf("Converted by string template: \"%s\"\n", str_from_template);
}

这是我收到的警告:

/home/mpiroc/Desktop/unicode_to_string/unicode_to_string.vala.c: In function ‘g_unichar_to_string’:
/home/mpiroc/Desktop/unicode_to_string/unicode_to_string.vala.c:26:2: warning: passing argument 2 of ‘g_unichar_to_utf8’ discards ‘const’ qualifier from pointer target type [enabled by default]
/usr/include/glib-2.0/glib/gunicode.h:684:11: note: expected ‘gchar *’ but argument is of type ‘const gchar *’

这是警告中提到的生成的c代码:

 18 static gchar* g_unichar_to_string (gunichar self) {
 19     gchar* result = NULL;
 20     gchar* _tmp0_ = NULL;
 21     gchar* str;
 22     const gchar* _tmp1_;
 23     _tmp0_ = g_new0 (gchar, 7);
 24     str = (gchar*) _tmp0_;
 25     _tmp1_ = str;
 26     g_unichar_to_utf8 (self, _tmp1_);
 27     result = str;
 28     return result;
 29 }

好像_tmp_好像不应该标注const,但这是valac生成的,不是我直接写的。难道我做错了什么?或者这是valac 中的错误?代码按预期运行,但我尽量避免出现警告。

【问题讨论】:

    标签: unicode utf-8 vala


    【解决方案1】:

    Add --disable-warnings command-line option

    IIRC Vala 编译器也可以使用 --disable-warnigs 命令行选项。

    编辑:

    gcc commandline options

    对不起,valac 是转译器,所以一旦 valac --ccode 输出,然后 需要运行 gcc 或其他编译器。

    $ valac --ccode unicode_to_string.vala
    $ gcc -o unicode_to_string -w unicode_to_string.c `pkg-config --libs --cflags gobject-2.0`
    

    【讨论】:

    • 你也可以只做valac -X -w -o unicode_to_string unicode_to_string.vala。 --Xcc/-X 将告诉 valac 将提供的参数传递给 CC。
    【解决方案2】:

    Vala 编译器不会生成临时变量const。您可以放心地忽略有关 const-ness 的警告。

    【讨论】:

    • 不是吗?那为什么生成的代码const中是_tmp1_呢?这显然是一个临时变量。
    • 错误。未正确生成变量或参数const。在这种特殊情况下,g_unichar_to_stringunichar 的实例方法,但它没有将参数self 标记为const。 Vala 复制的临时变量是const,因为编译器知道它不打算修改它们。这就是导致上述错误的原因:unichar 的临时副本是const,而unichar.to_string() 的实例方法没有将self(即实例参数)标记为const
    • 不,这不是问题所在。问题是g_unichar_to_utf8 的第二个参数是一个非常量指针(这是有道理的,因为它将被修改),但代码将_tmp1_ 作为参数传递,这是一个常量指针。所以问题不在于 valac 在某个地方忘记了一个 const,而是它在不属于它的地方添加了一个。
    • 这就是 Vala C 类型生成器的问题所在:const char *char const * 之间的区别意味着后者但打印前者。无论如何,大多数与const 相关的警告都会被安全地忽略。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多