Smich
Smich

Reputation: 435

Self-referential struct defined in a C header file produces error

I am trying to write a header file containing macros for a generic type doubly linked list.

The nodes are defined as follows:

#define node(T)                \
    struct node_##T            \
    {                          \
        T val;                 \
        struct node_##T *next; \
        struct node_##T *prev; \
    }

I am then using node(T) to create a linkedlist(T) struct:

#define linkedlist(T)       \
    struct linkedlist_##T   \
    {                       \
        unsigned int count; \
        node(T) *head;      \
        node(T) *end;       \
    }

Finally, a linkedlist(Student) ll; is declared, which calls node(Student) and produces this error at compilation:

error: redefinition of ‘struct node_Student’

The error occurs at the line at which struct node_##T is first declared.

Interestingly, the error goes away when I insert a semicolon at the end of the struct definition like this:

        . . . .
        struct node_##T *prev; \
    };

However, this cannot be done as then the declaration node(T) N; would be impossible.

What could be a possible fix?

Upvotes: 1

Views: 52

Answers (1)

Tanveer Badar
Tanveer Badar

Reputation: 5512

Compiler is completely correct. You are redeclaring your struct. Change the linked list definition to say

#define linkedlist(T)       \
    struct linkedlist_##T   \
    {                       \
        unsigned int count; \
        struct node_##T *head;     \
        struct node_##T *end;      \
    };

instead. You'll need to have a separate node(T) line for each T before linkedlist(T) somewhere.

Upvotes: 2

Related Questions