上下文
我们有三个文件:
- module.h:它包含一个结构的声明,
- module.c:它包含结构的定义,
- main.c:它包含结构的一个实例。
目标是通过使用 API (module.h) 而不是直接通过操作结构成员来使用 main.c 中的结构。这就是为什么结构的定义在 module.c 而不是在 module.h 中。
代码
模块.h
#ifndef MODULE_H
#define MODULE_H
typedef struct test_struct test_struct;
void initialize_test_struct(int a, int b, test_struct * test_struct_handler);
#endif
模块.c
#include "module.h"
struct test_struct
{
int a;
int b;
};
void initialize_test_struct(int a, int b, test_struct * test_struct_handler)
{
test_struct_handler->a = a;
test_struct_handler->b = b;
}
主.c
#include "module.h"
int main(void)
{
test_struct my_struct; // <- GCC error here
test_struct * my_struct_handler = &my_struct;
initialize_test_struct(1, 2, my_struct_handler);
return 0;
}
问题
如果我们用 GCC 编译这些文件,我们会得到以下错误:
main.c:7:17: error: storage size of ‘my_struct’ isn’t known
问题
我们如何才能强制使用 API,从而禁止直接使用结构的成员来操作结构,结构的声明和定义与 main.c 在不同的模块中?
最佳答案
由于 test_struct
的定义对您的 main
函数不可见,因此您无法创建该对象的实例,也无法访问其成员。但是,您可以创建指向它的指针。所以你需要在 module.c 中为一个实例分配内存并返回指向它的指针的函数。您还需要函数来读取成员。
在 module.h 中:
test_struct *allocate_test_struct();
int get_a(test_struct *p);
int get_b(test_struct *p);
在 module.c 中:
test_struct *allocate_test_struct()
{
test_struct *p = malloc(sizeof(test_struct));
if (!p) {
perror("malloc failed");
exit(1);
}
return p;
}
int get_a(test_struct *p)
{
return p->a;
}
int get_b(test_struct *p)
{
return p-b;
}
在 main.c 中:
test_struct * my_struct_handler = allocate_test_struct()
initialize_test_struct(1, 2, my_struct_handler);
printf("%d\n", get_a(my_struct_handler));
printf("%d\n", get_b(my_struct_handler));
free(my_struct_handler);
关于c - 在 main.c 中使用在 module.h 中声明并在 module.c 中定义的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53947638/