views:

81

answers:

3

Okay, strange question time!

I'm refactoring some old C++ code that declares a bunch of arrays like so:

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

And so forth. These are scattered about in the source files, and are used right where they're declared.

However, I would like to move them into a single source file (mostly because I've come up with a way of auto-generating them). And, of course, I naively try to make a header for them:

static SomeStruct SomeStructArray[];

Actually, even I know that's wrong, but here's the compiler error anyway:

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

So, I guess, what's the right way to do this?

+6  A: 

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

Then, in your header you need to add an extern to each declaration.

Finally, of course, you'll need to ensure that when you have an array of SomeStruct (for example), that the definition of SomeStruct is visible before you attempt to define an array of them.

Jerry Coffin
Ahhh. That makes sense. Also, yeah, I omitted the irrelevant parts of the code, since they're irrelevant :)
Mike Caron
Thats so neat!!!!!
Praveen S
A: 

Try to use

.h file:

extern SomeStruct SomeStructArray[];

.cpp file:

extern SomeStruct SomeStructArray[] = {
  {1, 2, 3},
  {4, 5, 6},
  {NULL, 0, 0}
}
Unick
Why `extern` on the array itself? Doesn't it get `extern`'d from the declaration?
Mike Caron
A: 

Create a header file and put this in it:

extern SomeStruct SomeStructArray[];

then put your existing code into a source file (not a header file):

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

And the downside, you can't 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 could add extra variables to get around this.

This was tested using DevStudio2k5.

Skizz
This is not true, my compiler (even in Standard conforming mode) says:*error: ‘SomeStructArray’ was declared ‘extern’ and later ‘static’*
schot
Ah, I see what I've done. I didn't include the header declaring the array into the source file containing the definition of the array. Fixed it.
Skizz