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?
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.
Try to use
.h file:
extern SomeStruct SomeStructArray[];
.cpp file:
extern SomeStruct SomeStructArray[] = {
{1, 2, 3},
{4, 5, 6},
{NULL, 0, 0}
}
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.
精彩评论