Search code examples
c++carraysstructforward-declaration

Forward declarations for variables?


I have some C code that I have to port to C++. The code has a structure

struct A { 
    ...
    struct A * myPtr;
}

And now two global arrays are declared and initialized like this:

//Forward declaration of Unit
struct A Unit[10];

struct A* ptrUnit[2] = { Unit, Unit+7 };
struct A Unit[10] = { { .., &ptrUnit[0] }, 
                      ... };

Now while this works fine in C, it gives an error in C++ (variable redeclared). Aren't variables allowed to be forward-declared in C++?


Solution

  • In C++, a variable declaration must be prefixed with extern:

    extern A Unit[10];
    
    // ...
    
    A Unit[10] = { ... };
    

    (Note that in C++ you can omit the leading struct.)