tags:

views:

87

answers:

2

In C, when defining an array I can do the following:

int arr[] = {5, 2, 9, 8};

And thus I defined it and filled it up, but how do I define it in my .h file, and then fill it in my .c?

Like do something like

int arr[];
arr = {5, 2, 9, 8};

I'm pretty new to C, not sure how it would look

any suggestions?

+9  A: 

Normally, you'd put:

extern int arr[];

In the .h file, and:

int arr[] = { 5, 2, 9, 8};

In the .c file.

Edit: Dale Hagglund and KevinDTimm raise good points: you only want to put the initialization in one .c file, and you only need to put anything in the .h file if you're going to access arr from code in more than one .c file.

Jerry Coffin
If your program has multiple C files, make sure that only one defines the array, that is, contains the second line above. The rest only need to declare it by including the `.h` file containing `extern int arr[];`
Dale Hagglund
I would question the need to define in the .h at all, unless there is a sharing occurring. Maybe point the OP in that direction?
KevinDTimm
A: 

You can use include guards to prevent the assignemnt from happening multiple times, but putting the assignment into headers is a very bad practice in my opinion. Put the intialization in a c file, in an init function instead and extern the array in the h file.

Michael Dorgan