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?
The header file -- the whole thing: array.h The preprocessor statements and the using statement at the beginning of the . h file are similar (except a different identifier, ARRAY_H, to match the filename is used): #ifndef ARRAY_H #define ARRAY_H #include < iostream > using namespace std; Consider the class definition.
As in case of scalar variables, we can also use external or global arrays in a program, i. e., the arrays which are defined outside any function. These arrays have global scope. Thus, they can be used anywhere in the program.
The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.
int array[4] = {1,2,3,4}; will work, but putting objects in headers is generally a bad idea because it is easy to accidentally define the object multiple times just by including the header more than once. Inclusion guards are only a partial fix for that problem.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With