【问题标题】:Self-referential struct defined in a C header file produces errorC 头文件中定义的自引用结构产生错误
【发布时间】:2020-01-24 17:31:40
【问题描述】:

我正在尝试编写一个包含泛型双向链表宏的头文件。

节点定义如下:

#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; 将是不可能的。

有什么可能的解决方法?

【问题讨论】:

  • 注意struct node_##T 在T 为long long 时将无法正常工作。
  • 有趣.... 尝试使用 C 宏实现 C++ 模板。也许你应该升级到 C++!

标签: c struct c-preprocessor header-files user-defined-data-types


【解决方案1】:

编译器完全正确。您正在重新声明您的结构。把链表定义改成说

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

相反。您需要在某处的 linkedlist(T) 之前为每个 T 有一个单独的 node(T) 行。

【讨论】:

  • 如果您尝试使用 linkedlist(T) 声明多个变量,您仍然会得到重新定义。
  • 需要#if / #endif 守卫帮忙吗?
  • 非常感谢,现在我明白错误所在了。但是,linkedlist(T) 用作类型,因此无法将node(T); 添加到定义中。我刚刚编辑了问题以澄清这一点。
  • 然后只需在该宏本身之外执行node(T)。您只需在代码中执行一次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-15
  • 1970-01-01
  • 1970-01-01
  • 2012-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多