【问题标题】:how to make a static struct from typedef [duplicate]如何从 typedef 制作静态结构 [重复]
【发布时间】:2019-11-26 09:05:17
【问题描述】:

我有一个头文件list.h 和一个源文件list.c,它们定义了list.h 中的函数。 我这里有一个结构:

    typedef struct ListNode{
 struct ListNode* next;
 struct ListNode* prev;
 void *value;
    }Node;
    typedef struct List{
 Node *first;
 Node *last;
 int count;
    }List;

当编译器不接受同时使用 static 和 typedef 时,如何使它们仅对 list.h 中的函数可见?这些是我在 list.h 中声明的函数:

    List *List_create();
    void List_destroy(List *list);
    void *List_remove(List *list,Node *node);

【问题讨论】:

  • 您的意思是希望结构类型仅在list.c 中可见,还是要声明这些类型的静态变量?
  • 在声明变量时使用静态,而不是在typedef中。
  • 是的,我希望结构类型仅在 list.c 中可见。
  • 我已经编辑过了,抱歉我没有检查就粘贴了我的代码。
  • @ThomasJager 我确实尝试过,但编译器会抛出错误“在静态之前预期的说明符限定符列表”。该站点中的某个人还提到您不能在结构中声明静态变量。

标签: c struct static


【解决方案1】:

您可以使用指向不透明结构的指针来隐藏结构ListNode 的内容。在标头中,使用仅包含不透明的声明

typedef struct ListNode Node;
typedef struct List List;

和函数声明。这些告诉编译器结构和 typedef 存在,但不告诉编译器包含什么。

list.c 中,包含完整的声明,但不要作为 typedef,因为头文件已经告诉编译器有关 typedef 的名称。

struct ListNode {
    /* contents */
};
struct List {
    /* contents */
};

这样结构的内容在其他C文件中是不可用的,但list.c中的函数仍然可以使用它们。这也意味着其他 C 文件无法创建这些结构的新实例,除非使用 list.h 中提供的函数。

【讨论】:

  • 我应该如何在 list.c 中声明它?像 typedef struct ListNode {element..} Node?
猜你喜欢
  • 2012-09-08
  • 2012-08-21
  • 2021-11-06
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 2011-07-06
相关资源
最近更新 更多