Extern const int, multiple file help, c++

Hello,
I'm currently working on a project that needs useage of extern const variables, however i get the error; "error C2370: 'x' : redefinition; different storage class". so i wrote up a test to see if i could get any progress with it. However i couldnt.

Header file:
1
2
3
4
5
6
7
8
9
10
11
12
#if !defined(__TEST_H)
#define __TEST_H


extern const int x = 10;


int Test[x];


#endif


cpp file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

//test



#include <iostream>
using namespace std;
#include "test.h"

const int x = 10;


int main() {




	return 0;
}



i also tried using only extern const int x
but it also gave me an error.
Can anybody please help me? =)
You should remove initialization of the variable in the header file and write simply in the header

extern const int x;
ok i did that, it helped for the value alone.

However now i ran into another problem it seems with array
i updated my test to this:

Header File :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#if !defined(__TEST_H)
#define __TEST_H


extern const int x;

class Test{
private:
	int tst[x];
public:
	void fill();
	void dsp();

};

#endif


Cpp file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;
#include "test.h"

const int x = 10;


int main() {
     Test a;
     a.fill();
     a.dsp();


	return 0;
}
void Test::fill() {

	for(int i = 0; i < x ; i++)
		tst[i] = i+2;

}
void Test::dsp() {

	for(int i = 0; i < x; i++)
		cout << tst[i] << endl;
}


And getting error :
error C2057: expected constant expression

which i expect is an issue with my array in the class.

so, thanks vlad, and do anyone know a solution to my new problem? =)
int tst[x];
it is trying to create array of size x, but x do not have a value. Value to it you are giving in another file.
x is a characteristic of your class array. So instead of x define an enumerator (or const static) the following way

1
2
3
4
5
6
7
8
9
class Test{
private:
               enum { SIZE = 10; };
	int tst[SIZE];
public:
	void fill();
	void dsp();

};

and in the main use

1
2
3
4
5
6
7
8
9
10
void Test::fill() {

	for(int i = 0; i < SIZE ; i++)
		tst[i] = i+2;

}
void Test::dsp() {

	for(int i = 0; i < SIZE; i++)
		cout << tst[i] << endl;

Last edited on
ah ok, thanks.

is there no way to define a const in main and then use a form of extern term in a seperate file?

by personal prefrence i prefer to keep my consts and globale variables in one file, like say, main.

EDIT: for use in determening the array size

Thanks again for the replies
Last edited on
you use x in class Test, class is an object which can not have external information (at least in theory). User of a class must not know how class works and class variables.
Topic archived. No new replies allowed.