fearless_fool fearless_fool - 2 months ago 8
C++ Question

How to make forward declaration of a struct in Arduino?

Imagine this highly contrived example: (Note this is for Arduino-flavored C, not ANSI C):

typedef struct _node {
int value;
struct _node *next;
} node;


Using this, I can construct a linked list of two nodes by building the list "backwards":

node nodeB = { 2, (node *)0 }; // end of list
node nodeA = { 1, &nodeB }; // A.next => B


But instead, what if I'd like to make a circularly linked list? This won't work:

node nodeA = { 1, &nodeB };
node nodeB = { 2, &nodeA };


since nodeB is not declared at the time that nodeA wants to reference it.

I could build the linked list at run time (dynamically allocate the nodes, then set up the
next
links). But is there a way to get a valid forward declaration at compile time?

Answer

This looks like a fairly ordinary situation where a forward declaration will work:

extern node nodeB;
node nodeA = { 1, &nodeB };
node nodeB = { 2, &nodeA };
Comments