Arrays in header

The following problem is a small part of my project. I have simplified the problem a lot.

I have declared both the array size and the array globally.

1
2
int N
double array[N]


Now using an empty function I am filling the array.

1
2
3
4
5
6
7
void arrayfill()
{
for(int i=0;i<N;i++)
{
array[i] = i;
}
}

Next, I have a function which sums over the elements of all the array depending upon integer variable var.
1
2
3
4
5
6
7
8
double sum(int var)
{
double s;
for(int i=0;i<var;i++)
{
s+=array[i];
}
return s;

Now, what I want is to create a header file which will have the empty function, another header which will have the sum function and finally from the main function I want to call sum(). The reason I am doing this is because I want to fill the array once and keep using sum() at many different places with different values of var.

Can anybody help?
Last edited on
I have declared both the array size and the array globally.

That's not legal C++. When declaring an array, the dimension must be a constant that's known at compile-time.

Now, what I want is to create a header file which will have the empty function, another header which will have the sum function and finally from the main function I want to call sum(). The reason I am doing this is because I want to fill the array once and keep using sum() at many different places with different values of var.


You should define the functions in CPP files, not header files. If you put the function definition in the header, you'll end up defining the same function multiple times, once in each translation unit, which the linker won't allow.

So define each function once, in a CPP file (they can be in the same file, or different ones, whichever you prefer). Then declare each function in a header file, that can be included in any other translation unit that needs to call it.

I would, however, strongly urge you not to use global variables. As you move to bigger projects, you'll find they cause more and more problems. It's much better to get into good habits early on, and avoid using them.
Last edited on
Topic archived. No new replies allowed.