用C语言在头文件中声明结构的任何方式而不必在其他文件中使用指针吗? [英] Any way in C to forward declare struct in header without having to use pointer in other files?

查看:308
本文介绍了用C语言在头文件中声明结构的任何方式而不必在其他文件中使用指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在list.h中有这个

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

,然后在list.c中定义它们:

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

除了在头文件中包含struct声明之外,我还能做些什么,以便在一些文件test.c中可以拥有:

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

就像也许以某种方式告诉编译器list_iter_t的存储大小?必须使用指针是很不方便的(不是因为它是指针,而是由于其他原因),但是同时我想尽可能地隐藏实现细节.

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.

推荐答案

简洁的回答是否".

告诉编译器struct的大小的方法是告诉它struct的结构细节.如果要分配对象而不是对象的指针,则编译器必须知道对象的完整类型.如果类型不完整,您也不能通过指向结构的指针来访问结构的成员.也就是说,编译器必须知道成员的偏移量和类型,才能生成正确的代码来访问someptr->member(以及分配somevalue或访问somevalue.member).

The way you tell the compiler the size of a struct is by telling it the details of how the struct 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 access someptr->member (as well as to allocate somevalue or access somevalue.member).

这篇关于用C语言在头文件中声明结构的任何方式而不必在其他文件中使用指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆