我一直在浏览Minix 1.1源代码,并注意到在定义或声明之前引用了一个struct类型。例如,main.c包含以下内容:
#include "file.h"
#include "fproc.h"
#include "glo.h"
#include "inode.h"
#include "param.h"
#include "super.h"
file.h包含以下内容:
EXTERN struct filp {
mask_bits filp_mode; /* RW bits, telling how file is opened */
int filp_count; /* how many file descriptors share this slot? */
struct inode *filp_ino; /* pointer to the inode */
file_pos filp_pos; /* file position */
} filp[NR_FILPS];
inode.h包含以下内容:
EXTERN struct inode {
unshort i_mode; /* file type, protection, etc. */
uid i_uid; /* user id of the file's owner */
file_pos i_size; /* current file size in bytes */
real_time i_modtime; /* when was file data last changed */
gid i_gid; /* group number */
links i_nlinks; /* how many links to this file */
zone_nr i_zone[NR_ZONE_NUMS]; /* zone numbers for direct, ind, and dbl ind */
/* The following items are not present on the disk. */
dev_nr i_dev; /* which device is the inode on */
inode_nr i_num; /* inode number on its (minor) device */
short int i_count; /* # times inode used; 0 means slot is free */
char i_dirt; /* CLEAN or DIRTY */
char i_pipe; /* set to I_PIPE if pipe */
char i_mount; /* this bit is set if file mounted on */
char i_seek; /* set on LSEEK, cleared on READ/WRITE */
} inode[NR_INODES];
请注意,struct filp包含一个成员filp_ino,它是一个指向inode类型的指针;但是,直到稍后才定义类型inode。
我假设您需要转发声明类型或在使用前定义它,但显然我错了。有人能指出我理解的正确方向1)为什么这是合法的; 2)编译器如何在不事先了解inode类型的情况下解析struct filp。
答案 0 :(得分:1)
您可以在不知道类型大小的情况下创建指向不完整类型(例如结构或联合类型)的指针,因此您可以使用:
struct anything *p;
在定义struct anything
的内部(在示例代码中anything
拼写为inode
之前)。您不能取消引用不完整的类型,但您可以创建指向它的指针。如果您不需要访问不完整类型的内部,则可以在不定义内部的情况下传递指针。这可以帮助您在C中创建不透明类型。