I have the following simple source
#include <iostream>
int main() {
int nv;
nv = 3;
int arr[nv] = { 0, 2, 5 };
return 0;
}
When compiling with GCC on system 1 I get
error: variable-sized object ‘arr’ may not be initialized.
When compiling with GCC on system 2 I get no errors.
Compilation flags are the same in both cases, see below.
What is the reason for this, and how can I get my code to compile in system 1? I suspected it was related to gcc version, but I found no information to support this suspicion.
In system 1:
$ g++ --version
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
...
$ make
g++ -MMD -g -g3 -Wall -Wunused -Wuninitialized -Wextra -fmessage-length=0 -std=gnu++11 -c -o obj/arrays_test.o src/arrays_test.cc
...
In system 2:
$ g++ --version
g++ (Ubuntu 5.5.0-12ubuntu1~16.04) 5.5.0 20171010
...
$ make
g++ -MMD -g -g3 -Wall -Wunused -Wuninitialized -Wextra -fmessage-length=0 -std=gnu++11 -c -o obj/arrays_test.o src/arrays_test.cc
...
The problem here is that you're using not one but two extensions.
The first extension, as noted already, is that you're using C99 VLA's in C++. That's a documented GCC extension.
The second extension is that even C99 doesn't allow initializers for VLA's :
C99 §6.7.8 [Initialization]
The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.
(In C11 you'll find this restriction in §6.7.9). But as the linked GCC page shows, this is not an official Gnu extension. The C99 restriction still stands. You'll need to use assignment instead of initialization.