gpt4 book ai didi

c - 为什么在 C 中将类型定义为指向未定义结构的指针是有效的?

转载 作者:行者123 更新时间:2023-12-02 09:15:51 25 4
gpt4 key购买 nike

我正在深入研究第 3 方代码库,发现将类型声明为指向未定义结构的指针显然是有效的。作为一个最小的工作示例,考虑一个 C 文件 test.c 只包含:

typedef struct foo *bar;

令我惊讶的是,使用该命令编译该文件没有任何问题

gcc test.c -shared

为什么编译器不会提示 struct foo 没有在任何地方声明?

我的环境是带有gcc的Ubuntu 16.04(Ubuntu 5.4.0-6ubuntu1~16.04.5)5.4.0 20160609。

最佳答案

上面的声明创建了struct foo前向声明。虽然您无法访问其成员,但可以对指向它的指针进行操作。

这通常称为不透明类型,用于向库的用户隐藏库的实现细节。

例如,库实现可能包含以下内容:

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);
}

该库的头文件可能如下所示:

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 函数创建该结构的实例,并使用 set1get1 函数来读取/更新成员(member)。但是,用户无法在不通过接口(interface)函数之一的情况下创建 struct foo 的实例或访问成员。

关于c - 为什么在 C 中将类型定义为指向未定义结构的指针是有效的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47229612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com