c - C 中有什么方法可以在头文件中转发声明结构而不必在其他文件中使用指针?

标签 c struct header-files forward-declaration

假设我在 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 的存储大小?不得不使用指针很不方便(不是因为它是指针,而是其他原因),但同时我想尽可能隐藏实现细节。

最佳答案

简洁的答案是“否”。

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

关于c - C 中有什么方法可以在头文件中转发声明结构而不必在其他文件中使用指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7278495/

相关文章:

c - C中的动态数组和指针

c - 使用##连接宏常量

c - 如何在c和mingw中创建复选框

c - 如何在C中返回ascii字符的索引

c - 如何将文件读入结构数组?

c - 有没有办法为 C 文件生成包含映射?

c++ - 我应该使用哪个头文件而不是#include <bits/stdc++.h>

c - 直接返回结构体还是填充指针?

c - 如何使用 C 选择数组中的多个元素?

go - 是否可以在 golang 中使用批量赋值?