1

I have a class like this:

/* ClassA.h */
class ClassA{
public:
  static const size_t SIZE = 10;
  int array[SIZE];
  funcA();
  funcB();
  ...
};

And, in the other cpp file, there is code like:

min(ClassA::SIZE, other_variable);

But, I cannot build this code, and I get an error like below (in latest cc in Mac OS X, Apple LLVM 4.2 (clang-425.0.28))

Undefined symbols "ClassA::SIZE" ...

It is probably because "SIZE" is defined within the header file and can be used like a macro, ClassA.o does not contain "SIZE" as symbol. At the same time, referring code somehow requires symbol when used inside "min" template. (I can check it by 'nm' command that ClassA.o does not contains "SIZE" symbol, but referring code's object file contains "SIZE" symbol.)

ClassA.o can contains "SIZE" symbol by defining literal number in ClassA.cpp like below:

const int ClassA::SIZE = 10; 

But in this case, there is another error like below, due to an array being defined in header file.

error: fields must have a constant size: 'variable length array in structure' extension will never be supported

The original code worked in some older complier (LLVM 4.0). Any good idea to solve this situation?

2
  • 1
    Do you use namespaces? You might have to add the namespace if you do.
    – Djon
    Commented May 30, 2013 at 9:46
  • I have a very similar issue, but with C, not C++. I also find out, that gcc preserves the static const variables in it's object files. (May not apply in your case?) I do more research before I post a question/answer here.
    – Adam L. S.
    Commented Jun 29, 2013 at 20:31

3 Answers 3

5

You need to provide a definition for ClassA::SIZE, but still give the constant integral 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
1
/* ClassA.h */
class ClassA{
public:
  static const size_t SIZE = 10;
  int array[SIZE];
  funcA();
  funcB();
  ...
};
const size_t ClassA::SIZE;

That should work.

1
  • const data members can be defined in- class Commented May 30, 2013 at 9:52
0

Why not use an enum?, you could define the array as a static variable in a static method (so everything is in the header file)

class ClassA {
    public:
    enum {SIZE=10;};
    static int *array() { static int arr[SIZE]; return arr; }
};

Not the answer you're looking for? Browse other questions tagged or ask your own question.