C 中有什么方法可以在标头中转发声明结构,而不必在其他文件中使用指针?
假设我在 list.h 中有这个:
typedef struct list_t list_t;
typedef struct list_iter_t list_iter_t;
list_iter_t iterator(list_t *list);
然后在 list.c 中定义它们:
typedef struct node_t {
...
} node_t;
struct list_iter_t {
node_t *current;
// this contains info on whether the iterator has reached the end, etc.
char danger;
};
struct list_t {
...
}
list_iter_t iterator(list_t *list) {
list_iter_t iter;
...
return iter;
}
除了在头文件中包含结构声明以便在某些文件 test.c 中我可以有:
#include "list.h"
void foo(list_t *list) {
list_iter_t = iterator(list);
...
}
就像也许告诉编译器以某种方式确定 list_iter_t 的存储大小?必须使用指针很不方便(不是因为它是指针,而是因为其他原因),但同时我想尽可能隐藏实现细节。
Suppose I have this in list.h:
typedef struct list_t list_t;
typedef struct list_iter_t list_iter_t;
list_iter_t iterator(list_t *list);
and then define them in list.c:
typedef struct node_t {
...
} node_t;
struct list_iter_t {
node_t *current;
// this contains info on whether the iterator has reached the end, etc.
char danger;
};
struct list_t {
...
}
list_iter_t iterator(list_t *list) {
list_iter_t iter;
...
return iter;
}
Is there anything I can do aside from including the struct declaration in the header file so that in some file test.c I can have:
#include "list.h"
void foo(list_t *list) {
list_iter_t = iterator(list);
...
}
Like maybe tell the compiler the storage size of list_iter_t somehow? It's inconvenient to have to use a pointer (not because it's a pointer, but for other reasons), but at the same time I would like to hide the implementation details as much as possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简洁的答案是“否”。
告诉编译器 struct 大小的方法是告诉它 struct 的结构细节。如果要分配一个对象,而不是指向该对象的指针,编译器必须知道该对象的完整类型。如果类型不完整,您也无法通过指向结构的指针访问结构的成员。也就是说,编译器必须知道成员的偏移量和类型才能生成正确的代码来访问
someptr->member
(以及分配somevalue
或访问 <代码>somevalue.member)。The succinct answer is "No".
The way you tell the compiler the size of a
struct
is by telling it the details of how thestruct
is structured. If you want to allocate an object, rather than a pointer to the object, the compiler must know the complete type of the object. You also can't access the members of a structure via a pointer to the structure if the type is incomplete. That is, the compiler must know the offset and type of the member to generate the correct code to accesssomeptr->member
(as well as to allocatesomevalue
or accesssomevalue.member
).使用如下虚拟定义可以告诉编译器结构的大小:(
使用正确的定义而不是可用于实现文件)。
从形式上来说,这会导致未定义的行为;不过,它在实践中可能会有一定作用。
不过,您可能最好只包含正确的结构定义,并留下注释,大意是代码不应触及内部成员。
It is possible to tell the compiler the size of the structure, using a dummy definition like:
(with the proper definition instead available to the implementation file).
Formally this causes undefined behaviour; it is likely to somewhat work in practice, though.
You are probably best off just including the proper structure definition though, and leaving a comment to the effect that code should simply not touch the internal members.