Defining a static constant variable in C ++
I have a class like this:
/* ClassA.h */
class ClassA{
public:
static const size_t SIZE = 10;
int array[SIZE];
funcA();
funcB();
...
};
And in another cpp file there is a code like this:
min(ClassA::SIZE, other_variable);
But I cannot generate this code and I am getting an error like below (in the last cc on Mac OS X, Apple LLVM 4.2 (clang-425.0.28))
Undefined symbols "ClassA::SIZE" ...
Probably because "SIZE" is defined in the header file and can be used as a macro, ClassA.o does not contain "SIZE" as a symbol. At the same time, the reverse code somehow requires a character when used inside the "min" pattern. (I can check it with the "nm" command that ClassA.o does not contain the "SIZE" character, but the code object file reference does contain the "SIZE" character.)
ClassA.o can contain the character "SIZE", specifying an alphabetic number in ClassA.cpp, as shown below:
const int ClassA::SIZE = 10;
But in this case, there is another error, as shown below, due to the array being defined in the header file.
error: fields must have a constant size: 'variable length array in structure' extension will never be supported
The source code worked with some older compilers (LLVM 4.0). Any good idea to deal with this situation?
source to share
You need to provide a definition for ClassA::SIZE
, but still give a constant integer value at the point of declaration:
/* ClassA.h */
class ClassA{
public:
static const size_t SIZE = 10; // value here
int array[SIZE];
funcA();
funcB();
...
};
/* ClassA.cpp */
const size_t ClassA::SIZE; // no value here
source to share