extern const int used as array size - expression must be constant error

I declare and initialize this constant in globals.cpp:
const unsigned SETT_OPTION_COUNT=4;
To make it accessible from other files, I make the const extern in globals.h:
extern const unsigned SETT_OPTION_COUNT;

However, when I want to use it as array size here:
1
2
3
4
5
6
7
8
bool create_settings(std::ofstream& file, const int values[SETT_OPTION_COUNT]) {
	for (size_t i=0; i<SETT_OPTION_COUNT; i++) {
		file << SETT_STRING_LOCALE[i] << "=" << values[i];
		if (i<SETT_OPTION_COUNT-1) 
			file << std::endl;
	}
	return true;
}


I get the error that the expression must be constant.
I do realise that static arrays must have constant array size (const or as a const numerical within []), but I don't understand why SETT_OPTION_COUNT is illicit in this context.
Does it have anything to do with extern not being used properly? I didn't get any errors pertaining to the use of extern though.

For now, the only solution I found is to make the function count the array size itself:
bool create_settings(std::ofstream& file, const int values[]);

P.S When calling the function I use the const too:
create_settings(ofs, values[SETT_OPTION_COUNT]);

Any help appreciated :)
Last edited on
The size has to be known when you declare the array. The easiest way to solve it is to initialize SETT_OPTION_COUNT in the header file without using extern.

Note that you don't need to specify the array size declaring the function parameter.

This line
 
bool create_settings(std::ofstream& file, const int values[SETT_OPTION_COUNT])
is exactly the same as this
 
bool create_settings(std::ofstream& file, const int values[])
Last edited on
Does it have anything to do with extern not being used properly?
Yes, do not use extern for constants instead move

const unsigned SETT_OPTION_COUNT=4;

to the header file and remove the extern statement.

For now, the only solution I found is to make the function count the array size itself:
That's ok. The SETT_OPTION_COUNT of the parameter is ignored anyway.

P.S When calling the function I use the const too:
That's wrong. It shouldn't even compile. Instead of the array you pass a single element beyound the end of the array.
Thank you both kindly for your replies. It solved the problem :)
Topic archived. No new replies allowed.