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++?
A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier. In the case of functions, this allows us to tell the compiler about the existence of a function before we define the function's body.
In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.
You will usually want to use forward declaration in a classes header file when you want to use the other type (class) as a member of the class. You can not use the forward-declared classes methods in the header file because C++ does not know the definition of that class at that point yet.
Forward declarations are mainly to avoid circular imports, where one file imports another file which imports the first file etc. Basically when you import a file, contents of the file are substituted at the point of import when you build your project, which is then fed to the compiler.
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
.)
struct A Unit[10]
is not a forward declaration of a variable. The term "forward declaration" normally refers to non-defining declarations, while struct A Unit[10]
is a definition. So in your code you are defining Unit
multiple times in the same source file. In C language it is allowed, since in C definitions without an initializer are tentative definitions. They may occur many times in the same translation unit. In C++ there's no such thing as tentative definition. In C++ multiple definitions are always illegal.
If you want a genuine forward declaration for a variable, you have to use the keyword extern
extern struct A Unit[10];
This will work in both C and C++. However, as a side effect, this will give Unit
external linkage. If you need a variable with internal linkage, then you are out of luck in C++, since in C++ it is not possible to forward-declare a variable with internal linkage. Meanwhile, in C tentative definitions will still help you to achieve that.
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