gpt4 book ai didi

c - 如何在另一个 .c 文件中使用前向声明的结构数据?

转载 作者:行者123 更新时间:2023-12-04 10:08:22 24 4
gpt4 key购买 nike

我有一个在 file.h 中向前声明的结构。该结构在 file1.c 中定义。我正在尝试使用 file2.c 中的结构。但它在 file2.c 中给我“错误:取消引用指向不完整类型的指针”。

文件.h

typedef struct foo foo;

file1.c

#include <file.h>

typedef struct foo {
int val;
} foo;

file2.c

#include <file.h>

struct foo *f;
.
.
.
printf("%d", f->val); <--Error here

如果我在 file.h 中定义结构,我没有任何问题。有什么办法可以在 file2 中使用 val 吗?

最佳答案

这称为不透明的 struct,当您想保护对成员的访问(一种私有(private)说明符)时很有用。

这样,只有file1.c 可以访问struct 的成员,以使其对您需要的其余.c 文件可见

1) 在.h文件中定义struct

2) 通过函数访问成员:

//file.h

typedef struct foo foo;
int foo_val(const foo *);

//file1.c

#include "file.h" // Always prefer "" instead of <> for local headers

struct foo { // Notice that you don't need to retypedef the struct
int val;
};

int foo_val(const foo *f)
{
return f->val;
}

//file2.c

#include "file.h"

struct foo *f;

printf("%d", foo_val(f));

关于c - 如何在另一个 .c 文件中使用前向声明的结构数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55628627/

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