简体   繁体   English

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

[英]How to use forward declared struct data in another .c file?

I have a struct which is forward declared in file.h. 我有一个在file.h中向前声明的结构。 The structure is defined in file1.c. 结构在file1.c中定义。 I'm trying to use the struct in file2.c. 我正在尝试在file2.c中使用struct。 But it is giving me "error: dereferencing pointer to incomplete type" in file2.c. 但它在file2.c中给了我“错误:取消引用指向不完整类型的指针”。

file.h file.h

typedef struct foo foo;

file1.c 在file1.c

#include <file.h>

typedef struct foo {
   int val;
} foo;

file2.c file2.c中

#include <file.h>

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

I don't have any issue if I define the struct in file.h. 如果我在file.h中定义结构,我没有任何问题。 Is there any way I can use val in file2? 有什么办法可以在file2中使用val吗?

This is called an opaque struct , is useful when you want to protect the access to the members (a kind of private specifier). 这称为opaque struct ,在您想要保护对成员(一种私有说明符)的访问时非常有用。

in this way, only file1.c can access the members of the struct , to make it visible to the rest of the .c files you need to 通过这种方式,只有file1.c可以访问struct的成员,使其对您需要的其余.c文件可见

1) Define the struct inside the .h file 1)在.h文件中定义struct

or 要么

2) Access the members through a function: 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)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM