Global array in header C?

Ok, weird question time!

I am refactoring old C ++ code that declares a bunch of arrays like this:

static SomeStruct SomeStructArray[] = { {1, 2, 3}, {4, 5, 6}, {NULL, 0, 0} } 

Etc. They are scattered around the source files and are used where they are declared.

However, I would like to move them to a single source file (mainly because I came up with a way to automatically generate them). And of course, I naively try to make a headline for them:

 static SomeStruct SomeStructArray[]; 

Actually, even I know this incorrectly, but here is a compiler error:

 error C2133: 'SomeStructArray' : unknown size arrays.h error C2086: 'SomeStruct SomeStructArray[]' : redefinition arrays.cpp 

So, I think, what is the right way to do this?

+4
source share
3 answers

If you are going to place all arrays in one file (and, apparently, access them from other files), you need to remove static from the definitions (which makes them visible only inside the same translation unit (i.e., file) )

Then in your headline you need to add extern to each ad.

Finally, of course, you need to make sure that if you have an array of SomeStruct (for example), then the definition of SomeStruct displayed before you try to determine the array of them.

+8
source

Try using

.h file:

 extern SomeStruct SomeStructArray[]; 

.cpp file:

 extern SomeStruct SomeStructArray[] = { {1, 2, 3}, {4, 5, 6}, {NULL, 0, 0} } 
0
source

Create a header file and put it in it:

 extern SomeStruct SomeStructArray[]; 

then put your existing code in the source file (not the header file):

 SomeStruct SomeStructArray[] = { {1, 2, 3}, {4, 5, 6}, {NULL, 0, 0} } 

Conversely, you cannot get the size of the array in other source files:

 size_t size = sizeof SomeStructArray; // doesn't work in any source file apart // from the one defining the array. 

You can add additional variables to get around this.

This has been tested with DevStudio2k5.

0
source

All Articles