// file: constants.h
#ifndef _CONSTANTS_H
#define _CONSTANTS_H
extern const char TAB[];
extern const int MAX_SIZE;
extern const char* FILENAME;
#endif //_CONSTANTS_H
//file: constants.cpp
#include "constants.h"
const char TAB[] = " ";
const int MAX_SIZE = 150;
const char* FILENAME = "test_scores.txt";
// main program file
#include "constants.h"
void main()
{
int scores[MAX_SIZE]; // gives the following compile errors:
.
.
.
.
}
Errors:
C:\Program Files\Microsoft Visual Studio\MyProjects\Test1\number1.cpp(36) :
error C2057: expected constant expression
C:\Program Files\Microsoft Visual Studio\MyProjects\Test1\number1.cpp(36) :
error C2466: cannot allocate an array of constant size 0
C:\Program Files\Microsoft Visual Studio\MyProjects\Test1\number1.cpp(36) :
error C2133: 'scores' : unknown size
Why isn't the compiler seeing the constant as a constant?
Thanks in advance,
David Churchill
Have you tried compiling just the code fragment you posted? It works fine
on my machine (NT 4 SP4 MSVC++ 6 SP2).
I'd look at the const MAX_SIZE as well. That is frequently #defined, and
you may be having a conflict with it somehow.
David Churchill wrote in message ...
You might try your hand at #define. :)
The immediate cause is because that's how VC links things.
If the const is in the same .cpp file, it seems like it will find it,
but if it is in another it will not find it when it needs it. It will
find it at run time though.
I've been reading Stroustrup trying to figure out if this is how
things are supposed to work. Have not come to any solid
conclusions yet. Discussion anybody?
Anyway, use the enum hack. Instead of using a const int,
define an enum in your .h file, and use that to initialize
your array bounds.
--
Dan Evens
(Standard disclaimers etc. No spam please.)
dan....@hydro.on.ca
Because a "const" value isn't necessarily a "constant" value. To be a
"constant" value, a "const" must have "internal linkage" (visibly only to
the current source file). "const" values have internal linkage by default,
but you explicitly overrule that with the "extern" qualifier.
Note that it's legal for MAX_SIZE to be declared "extern const int" in
constants.h, and as merely "int" in constants.cpp --- and as "extern int"
in, say, not-so-contants.h, which you include in other files. In such
cases, the inclusion of constants.h merely means that that particular source
file can't change the value of MAX_SIZE, but makes not guarantees about what
other modules do.
One think you can do, is to the definition of MAX_SIZE into the
constants.h (without the extern). This will define it in every module that
includes constants.h, but since they all will now have internal linkage,
this will not be a problem. Further, this will allow the compiler to treat
it as a true constant value, so that it probably will not have to generate
any storage space for it.
--
Truth,
James [MVP]
http://www.NJTheater.Com -and-
http://www.NJTheater.Com/JamesCurran