C 头文件中定义的自引用结构产生错误
Self-referential struct defined in a C header file produces error
我正在尝试为泛型双向链表编写一个包含宏的头文件。
节点定义如下:
#define node(T) \
struct node_##T \
{ \
T val; \
struct node_##T *next; \
struct node_##T *prev; \
}
然后我使用 node(T)
创建一个 linkedlist(T)
结构:
#define linkedlist(T) \
struct linkedlist_##T \
{ \
unsigned int count; \
node(T) *head; \
node(T) *end; \
}
最后,声明了一个 linkedlist(Student) ll;
,它调用 node(Student)
并在编译时产生此错误:
error: redefinition of ‘struct node_Student’
错误发生在首次声明struct node_##T
的行。
有趣的是,当我像这样在结构定义的末尾插入分号时,错误消失了:
. . . .
struct node_##T *prev; \
};
但是,这不能完成,因为那样声明 node(T) N;
是不可能的。
有什么可能的解决方法?
编译完全正确。您正在重新声明您的结构。将链表定义更改为 say
#define linkedlist(T) \
struct linkedlist_##T \
{ \
unsigned int count; \
struct node_##T *head; \
struct node_##T *end; \
};
相反。在某处 linkedlist(T)
之前,每个 T
需要单独的 node(T)
行。
我正在尝试为泛型双向链表编写一个包含宏的头文件。
节点定义如下:
#define node(T) \
struct node_##T \
{ \
T val; \
struct node_##T *next; \
struct node_##T *prev; \
}
然后我使用 node(T)
创建一个 linkedlist(T)
结构:
#define linkedlist(T) \
struct linkedlist_##T \
{ \
unsigned int count; \
node(T) *head; \
node(T) *end; \
}
最后,声明了一个 linkedlist(Student) ll;
,它调用 node(Student)
并在编译时产生此错误:
error: redefinition of ‘struct node_Student’
错误发生在首次声明struct node_##T
的行。
有趣的是,当我像这样在结构定义的末尾插入分号时,错误消失了:
. . . .
struct node_##T *prev; \
};
但是,这不能完成,因为那样声明 node(T) N;
是不可能的。
有什么可能的解决方法?
编译完全正确。您正在重新声明您的结构。将链表定义更改为 say
#define linkedlist(T) \
struct linkedlist_##T \
{ \
unsigned int count; \
struct node_##T *head; \
struct node_##T *end; \
};
相反。在某处 linkedlist(T)
之前,每个 T
需要单独的 node(T)
行。