static const member initialization problem

Pages: 12
@O.P.

Remember that you are compiling individual object files. In you last example, your resultant d.o file says to create a global array named MyArray, but it doesn't know the size. This .o file could, in theory, be linked to any object file that contains a definition of MyArraySize. This means that the size of MyArray could be different depending on the object file d.o is linked to. Because d.o will allocate memory, it needs to know exactly how much to allocate at compile time. That's why the size must be constant and known when the array is declared.
Last edited on
I see, MyArraySize would have to be constant. Interestingly the following code also does not compile when -pedantic-errors is set:

1
2
3
4
5
6
7
8
9
10
11
//c.cpp
extern const int MyArraySize = 256;

//d.cpp
extern const int MyArraySize;

int main(){
    int MyArray[MyArraySize];
    
    return(0);
}


Personally I think that's a weakness of the extern command. There seems to be no way to define a const int in one place that is used in multiple source files to define arrays.
Last edited on
Well, the following works:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//constant.h
const int MyArraySize = 256;

//a.cpp
#include "constant.h"

int main(){
    int MyArray1[MyArraySize];

    return(0);
}

//b.cpp
#include "constant.h"

int MyArray2[MyArraySize];

But the same approach does not work for the initial problem with const static members.
Topic archived. No new replies allowed.
Pages: 12