[Solved] “array bound is not an integer constant before ‘]’ token” when using multiple files [duplicate]

I’m having an issue with my neural net.
I’m storing the nodes that make up the network in an array, whose dimensions are set via-tweaks at compile time (the tweaks are all const).

The code worked fine until I decided to split it up into multiple files, but even with a extern declaration, it still says that “array bound is not an integer constant before ‘]’ token”.

Right now, this is the set-up:
In Network.h:

struct Network {
Node nodes [MNETWIDTH] [MNETLENGTH];
}

In Network.cpp:

Network::Network () {
Node nodes [MNETWIDTH] [MNETLENGTH];
}

The tweaks are declared in Misc.h (which is included in Network.h):

//////////Genetics Tweaks
extern int const MREPS;
extern int const BEINGSPER;
extern int const MUTRATE
extern double const BTOKEEP;
extern int const DNARANGE;
////////////Genetics Tweaks
////////////Network Tweaks
extern const int MNETWIDTH;
extern const int MNETLENGTH;
////////////End Network Tweaks

and then they’re defined in main.cpp

The nodes definiton needs to be in a header so it can be accessed by source files, but the constant tweaks can’t be in a header because then I get multiple declaration errors. I thought declaring them as extern would tell it to find the constant value elsewhere, but apparently not.

I tried changing it from an array to a 2D Vector, but that turned into an atrocious mess, so I’d really like it if I could get this to work.

I tried declaring nodes as extern in Network.h outside of the class without any size paramenters, then defining it in Network.cpp, but I still get the same error.
It seems it needs the constant definition in the same file that it’s being used in, but both the const variable and nodes are required in several files.

Any help here?

Thank you

Solution #1:

To be usable as a constant expression, a constant variable must be defined, not just declared. Assuming you want to use it from multiple translation units, remove the extern to give it internal linkage (so it can be defined in any unit that needs it), and add an initialiser to give the value.

Also, remove the local array declaration from the constructor. I’m not sure what you want that to do, but it doesn’t do anything useful.

the constant tweaks can’t be in a header because then I get multiple declaration errors

That’s because extern gives them external linkage, making them subject to the One Definition Rule.

I thought declaring them as extern would tell it to find the constant value elsewhere

It tells the compiler that the value will be available at run-time; but does not provide the compiler with the definition. The definition is needed to use the value in a constant expression.

Respondent: Mike Seymour
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.