2

我想隐藏结构定义,所以我在源文件中定义结构,如下所示:

//a.c
#include "a.h"

struct a_s
{
   int a;
   int b;
};

int func(a_t *a)
{
   printf("%d\n", a->a);
   return 0;
}


我在头文件中声明结构,如下所示:

//a.h
#ifndef TEST
#define TEST
#include <stdio.h>
#include <stddef.h>

typedef struct a_s a_t;
#endif

然后我使用 struct a_tint main.c 文件,如下所示:

#include "stddef.h"
#include "a.h"

int main()
{
   a_t a;
   a.a =2;
   func(&a);

   return 0;

}

但是当我编译 main.c 时gcc -c main.c,它失败了

main.c: In function ‘main’:
main.c:7:15: error: storage size of ‘a’ isn’t known
    struct a_s a;

为什么会失败?

4

3 回答 3

1

您不能创建尚未定义的结构的实例,因为编译器不知道要为其分配多少空间。

您无法访问尚未定义的 struct 成员,因为编译器不知道它们的类型。

但是,您可以使用指向尚未定义的结构的指针。这允许人们执行以下操作:

foo.h

typedef struct Foo Foo

Foo* Foo_new(int a, int b);
void Foo_destroy(Foo* this);
void Foo_set_a(Foo* this, int a);
void Foo_set_b(Foo* this, int b);
int Foo_get_a(Foo* this);
int Foo_get_b(Foo* this);
// ...

foo.c

#include "a.h"

struct Foo {
   int a;
   int b;
};

Foo* Foo_new(int a, int b) {
   Foo* this = malloc(sizeof(Foo));
   this->a = a;
   this->b = b;
   return this;
}

void Foo_destroy(Foo* this) { free(this); }
void Foo_set_a(Foo* this, int a) { this->a = a; }
void Foo_set_b(Foo* this, int b) { this->b = b; }
int Foo_get_a(Foo* this) { return this->a; }
int Foo_get_b(Foo* this) { return this->b; }
// ...

main.c

#include <stdio.h>
#include "foo.h"

int main(void) {
   Foo* foo = Foo_new(3, 4);
   Foo_set_a(foo, 5);
   printf("%d %d\n",
      Foo_get_a(foo),
      Foo_get_b(foo),
   );
   Foo_destroy(foo);
   return 0;
}

如果您想要一个真正不透明的类型,您甚至可以在 typedef 中包含指针。通常,这将是一个不好的做法,但在这种特殊情况下它具有一定的意义。有关概念的更多信息,请参阅此内容。

于 2019-12-04T04:59:10.477 回答
1

如果要隐藏结构定义,用户只能定义类型的指针,并且必须实现一个创建结构实例的api(通过malloc)和一个释放结构实例的api(通过free)

于 2019-12-04T02:49:55.360 回答
1

如果您实例化一个对象 A a,链接器会搜索 A 的定义,以便编译器知道它需要分配多少内存。它搜索 ah 并找到一个 typedef 但没有声明,因此错误是说它不知道 A 的大小。

如果程序的目的是对用户隐藏声明(和定义),则需要使用 A *a,因为这对编译器说“有一个类型 A,它的内存将从此内存位置”,因此在应该动态分配和释放内存的运行时之前不需要有关数据大小或布局的任何信息。

这种方法允许开发人员向用户公开界面,而用户无需了解有关数据结构的任何细节,并允许更新软件和修改数据结构,同时保持向外的标题相同(并保持测试通过)。

于 2019-12-04T02:28:40.777 回答