I am looking for the best know method for statically defining C/C++ data structures which need to be circularly linked. E.g. a tree where child and parent both need pointers to each other.
extern struct Op op_subops[4]; // fwd ref to children of ops
struct Op
{
const char *name;
struct Op *parent;
struct Op *children;
};
struct Op ops[128] = {
{"op",0,&op_subops[0]}
};
struct Op op_subops[4] = {
{"subop1",&ops[1],0},
{"subop2",&ops[1],0}
};
The above compiles (g++ 5.2). The extern
keyword seems to permit me to create a forward reference from ops
into ops_subops
, and the other direction works out naturally since ops
precedes ops_subops
.
The thing I don't like is that, I'd prefer both arrays to be static
(not create a publicly visible symbol in the object file).
I could use an integer index for one of the directions, but that seems a little hokey, and I'd rather just have the linker resolve the address for me.
Anyone have a magic keyword to make this work?
Thanks!
EDIT: I need to avoid things like C++ static constructors and bleeding-edge C++17 extensions (sadly). And my approach needs to platform independent.