views:

69

answers:

4

I'm writing some C and I have a lookup table of ints. I'm a little rusty... where do I declare and initialize the array so that I can use it in multiple C files? Can I declare it in an H file and initialize it in a C file?

+1  A: 

If I understand correctly, yes, you can do it. Read something about

extern static

keywords.

Tomasz Kowalczyk
Thanks, that's the hint I needed.
emddudley
I think the OP means "static" in a way, that doesn't correlate well with the meaning of the keyword `static` in the C language :).
Maciej Hehl
i've posted both as they both refer to visibility of a variable in C language - extern scope to oher files or make it static in file it appears.
Tomasz Kowalczyk
@emddudley - if it helped, please vote up ;]
Tomasz Kowalczyk
+1  A: 

You can declare it in a header file with extern, and define it in one of your source files. However, by definition, it can't also be static.

Oli Charlesworth
+3  A: 

Globals should be declared in a .h file and should be declared as extern, and then they should be defined in a .c file. See What's the best way to declare and define global variables and functions? from the comp.lang.c FAQ.

For arrays, some extra care might be necessary. See Q1.24 from the comp.lang.c FAQ too.

jamesdlin
+2  A: 

You define the array in one C file, and declare it as extern in another.

One common mistake is to equate the array with a pointer, and do something like:

// file1.c:
int array[] = { 1,2,3,4};

// file1.h:
extern int *array;

// file2.c:
#include "file1.h"

// use array

This will not work. You can treat the name of an array as a pointer in some situations, but this is not one of them. [Edit: The right thing to do is something like:

 // file1.h:
 extern int array[];
Jerry Coffin
But it works if you change `extern int *array;` to `extern int array[];`.
R..
@R: right -- now that you mention it, it probably isn't so good that my answer talks about what to avoid, but *not* how to do it right.
Jerry Coffin
"so good" is a subjective thing, but if you didn't edit, you wouldn't get my upvote :)
Maciej Hehl