【发布时间】:2019-12-04 02:03:44
【问题描述】:
我想隐藏结构体定义,所以我在源文件中定义结构体,像这样:
//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_t int main.c 文件,像这样:
#include "stddef.h"
#include "a.h"
int main()
{
a_t a;
a.a =2;
func(&a);
return 0;
}
但是当我通过 gcc -c main.c 编译 main.c 时,它失败了
main.c: In function ‘main’:
main.c:7:15: error: storage size of ‘a’ isn’t known
struct a_s a;
为什么会失败?
【问题讨论】:
-
在struct a_s定义后尝试#include "a.h"
-
在
main()中,名称a_t是不透明类型。您只能定义指向不透明类型的指针。 -
编译器无法在不知道要分配多少存储空间的情况下为
a_t分配存储空间(取决于结构定义)
标签: c struct opaque-pointers