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开发者_开发百科?
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.
If I understand correctly, yes, you can do it. Read something about
extern static
keywords.
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[];
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
.
精彩评论