I'm writing a code generator, well, actually a data generator that will produce data structures of this form (obviously the actual data structures are much more elaborate):
typedef struct Foo {
int a;
struct Foo* foo;
} Foo;
extern Foo f1;
extern Foo f2;
Foo f1 = {1, &f2};
Foo f2 = {2, &f1};
This is portable for all C and C++ compilers I have tried.
I would like to forward declare these struct instances as static so as not to pollute the global variable space, as in:
typedef struct Foo {
int a;
struct Foo* foo;
} Foo;
static Foo f1;
static Foo f2;
static Foo f1 = {1, &f2};
static Foo f2 = {2, &f1};
Although this works with gcc and probably all C compilers, the above code does not work with C++ compilers and results in a compile error:
error: redefinition of ‘Foo f1’
error: ‘Foo f1’ previously declared
I understand why this is happening in C++. Is there a simple workaround that does not involve using code at runtime to achieve the same effect that is portable to all C++ compilers without resorting to using a C compiler to compile certain files?