Tsuneo Yoshioka
Tsuneo Yoshioka

Reputation: 7874

Defining static const 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 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?

Upvotes: 1

Views: 1981

Answers (3)

Hassedev
Hassedev

Reputation: 631

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

That should work.

Upvotes: 1

Gearoid Murphy
Gearoid Murphy

Reputation: 12116

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; }
};

Upvotes: 0

gx_
gx_

Reputation: 4760

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

Upvotes: 5

Related Questions