为什么在C中将类型定义为指向未定义结构的指针有效? [英] Why is it valid to define a type as pointer to an undefined struct in C?
问题描述
我正在研究第3方代码库,发现将类型声明为未定义结构的指针显然是有效的.作为最低限度的工作示例,请考虑一个C文件test.c
,其中仅包含以下内容:
I was digging into a 3rd party code base and found that it is apparently valid to declare a type as a pointer to an undefined struct. As a minimum working example, consider a C file test.c
containing nothing but:
typedef struct foo *bar;
令我惊讶的是,使用该命令可以毫无问题地编译该文件
What surprises me is that this file compiles without any problems using the command
gcc test.c -shared
为什么编译器不抱怨未在任何地方声明struct foo?
Why does the compiler not complain about the struct foo not being declared anywhere?
我的环境是带有gcc的Ubuntu 16.04(Ubuntu 5.4.0-6ubuntu1〜16.04.5)5.4.0 20160609.
My environment is Ubuntu 16.04 with gcc (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609.
推荐答案
上面的声明创建了struct foo
的转发声明.尽管您无法访问其成员,但是可以在指向它的指针上进行操作.
The declaration above creates a forward declaration of struct foo
. Although you can't access its members, you can operate on a pointer to it.
这通常称为不透明类型,用于对库用户隐藏库的实现详细信息.
This is commonly referred to as an opaque type, and is used to hide implementation details of a library from users of the library.
例如,一个库实现可能包含以下内容:
For example a library implementation may contain the following:
lib.c:
struct foo {
int f1;
};
struct foo *init()
{
return malloc(sizeof(struct foo));
}
void set1(struct foo *p, int val)
{
p->f1 = val;
}
int get1(struct foo *p)
{
return p->f1;
}
void cleanup(struct foo *p)
{
free(p);
}
该库的头文件可能看起来像这样:
The header file for this library might look like this:
lib.h:
struct foo;
struct foo *init(void);
void set1(struct foo *p, int val);
int get1(struct foo *p);
void cleanup(struct foo *p);
该库的用户将使用init
函数创建该结构的实例,并使用set1
和get1
函数来读取/更新该成员.但是,如果不通过任何一种界面功能,用户将无法创建struct foo
的实例或访问成员.
The user of this library would use the init
function to create an instance of the struct and the set1
and get1
functions to read / update the member. The user can't however create an instance of struct foo
or access the members without going through one of the interface functions.
这篇关于为什么在C中将类型定义为指向未定义结构的指针有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!