GNOME Bugzilla – Bug 646970
const string[] doesn't work outside a class
Last modified: 2013-05-21 05:00:06 UTC
The following code works: class Test : Object { private const string[] _names = { "foo", "bar" }; public void show_names () { for (int i=0; i<this._names.length; i++) GLib.stdout.printf (this._names[i]); } } static int main () { var t = new Test (); t.show_names (); return 0; } whereas this breaks: static int main () { const string[] _names = { "foo", "bar" }; for (int i=0; i<_names.length; i++) GLib.stdout.printf (_names[i]); return 0; } with: /home/rgs/devel/breaks.vala.c: In function ‘_vala_main’: /home/rgs/devel/breaks.vala.c:21:2: error: initializer element is not constant /home/rgs/devel/breaks.vala.c:21:2: error: (near initialization for ‘_names[0]’) /home/rgs/devel/breaks.vala.c:21:2: error: initializer element is not constant /home/rgs/devel/breaks.vala.c:21:2: error: (near initialization for ‘_names[1]’) error: cc exited with status 256 Compilation failed: 1 error(s), 0 warning(s) Whats the difference of initializing a const string[] as a class member vs doing it inside main () ?
This issue still exists in version Vala 0.14.0.1-e5d2
I wonder if this might help: http://gcc.gnu.org/onlinedocs/gcc-4.5.0/gcc/Compound-Literals.html#Compound-Literals
I'm still seeing this in valac 0.20.1: $ cat test.vala int main() { const string[] A = { "a" }; (void)A; // Suppress unused warning. return 0; } $ valac --version Vala 0.20.1 $ valac test.vala /home/chaz/Desktop/test.vala.c: In function ‘_vala_main’: /home/chaz/Desktop/test.vala.c:19:2: error: initializer element is not constant /home/chaz/Desktop/test.vala.c:19:2: error: (near initialization for ‘A[0]’) /home/chaz/Desktop/test.vala.c: In function ‘main’: /home/chaz/Desktop/test.vala.c:27:2: warning: ‘g_type_init’ is deprecated (declared at /usr/include/glib-2.0/gobject/gtype.h:669) [-Wdeprecated-declarations] error: cc exited with status 256 Compilation failed: 1 error(s), 0 warning(s) (I'm ignoring the warning about g_type_init.) The issue is that valac isn't generating the correct C code here. If I run valac -C test.vala, it doesn't complain. It's only when it invokes cc that the error occurs.
commit ff4832bf273f8afaa501417d60d2e5c836ad6145 Author: Jürg Billeter <j@bitron.ch> Date: Tue May 21 06:52:02 2013 +0200 Fix C code generated for local string array constants Fixes bug 646970.