-
const extern
I am trying to initialize an array in one of my header files from an external constant number, but I get the error: size of member 'arraysize' is not constant. Am I going about this wrong, or is there a way to do what I'm trying to do? I want to be able to control all array sizes with constants in the main module. The following below is the sample code.
/* main module*/
#include <iostream>
#include <stdlib.h>
#include "cat.h"
typedef unsigned short int ushort;
const ushort arraysize = 32;
int main()
{
cat boots;
strcpy(boots.name, "Boots");
cout >> boots.name;
return 0;
}
/* End of Main Module */
/* cat.h */
typedef unsigned short int ushort;
const extern ushort arraysize;
//extern const ushort arraysize; //Tried this both ways
class cat
{
ushort age;
char name[arraysize];
};
/* End of cat.h */
-
I don't use globals so I don't really have any experience to base this around, but initially I don't think that this can be done -- at least not in the manner that you are attempting to do it.
Why?
Because you are initializing the constant in a different module. The array declaration has to know the size of the array from within the module prior to linking so that it knows how much stack space to use. Since it doesn't know the size from within that module during its compilation, it can't figure out how much space to make the array take up. It will probably work if you initialize the constant from within the module that you are using it (note me saying probably), but from the way you are talking, you are using it in array declarations in multiple modules.
If that is the case, then just use enum or don't extern the constant and just define it from within the header (you can do this because it's a constant), or *eek* #define.
Otherwise, you'll have to settle for dynamic allocation of the array with new and delete [].
-
The value of arraysize must be something useful before the first use. This is basically what you have (which breaks):
Code:
#include <iostream>
#include <cstring>
//#define TEST
typedef unsigned short ushort;
#ifdef TEST
const ushort arraysize = 32;
#else
extern const ushort arraysize;
#endif
class cat
{
public:
ushort age;
char name[arraysize];
};
#ifdef TEST
extern const ushort arraysize;
#else
const ushort arraysize = 32;
#endif
int main()
{
cat boots;
strcpy(boots.name, "Boots");
std::cout<< boots.name;
return 0;
}
Try switching things around by uncommenting #define TEST and it works perfectly. This is because arraysize has a usable value before its first use, unlike when TEST is commented out.
-Prelude