C结构中的类型不完整 [英] Incomplete type in C struct

查看:100
本文介绍了C结构中的类型不完整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下项目结构:

文件-a.h

#pragma once

 struct best_fit_struct {
    void *next;
    size_t size;
};

文件-b.h

#pragma once
typedef struct mm_t {
  int type;
  union {
      struct best_fit_struct best_fit_mm;
  } per_mm_struct;
  void *memory;
} mm_t;

文件-b.c

#include "a.h"
#include "b.h"

在使用gcc -c b.c编译b.c时,会引发以下错误

on compiling b.c using gcc -c b.c, it throws the following error

file best_fit_mm has incomplete data type

我在b.h之前加入了a.h,所以排序对我来说很合适.

I have included a.h before b.h, so the ordering looks proper to me.

令人惊讶的是,如果我在b.h中加入了a.h,事情就会解决.

Surprisingly, if I include a.h inside b.h, things gets resolved.

推荐答案

编译器必须知道每种数据类型的整个布局.例如.聚合中的每个字段,其偏移量(请参见 offsetof ),其大小(请参见 sizeof ),其对齐方式(请参见

The compiler has to know the entire layout of each data type. E.g. each field in aggregates, its offset (see offsetof), its size (see sizeof), its alignment (see alignof) and its type.

因此,编译器需要了解所有struct a(其中的所有字段)才能弄清struct b的布局(应该在struct b的定义点上知道这一点).

So the compiler needs to know all of struct a (all the fields there) to figure out the layout of struct b (and that should be known at the definition point of struct b).

在实践中,最好在标题b.h的开头附近添加#include "a.h".当然,您想在头文件中添加包含防护.

In practice, you'll better add #include "a.h" near the start of your header b.h. Of course you want to add include guards in your header files.

顺便说一句,我的首选是避免有许多小标头,而我更喜欢有一些大标头,甚至对于一个小型项目,甚至是一个通用标头(您可以 pre-compile gcc,请参见答案)

BTW, my preference is to avoid having many small headers, and I prefer have a few large ones, perhaps even one single common header for a small project (which you might pre-compile with gcc, see this answer)

有时,要调试与预处理器相关的错误,您可能会要求获取预处理后的表单(例如,使用gcc -C -E source.c > source.i然后在source.i中使用编辑器或分页器进行查找).

Sometimes, to debug preprocessor related bugs, you might ask to get the preprocessed form (e.g. using gcc -C -E source.c > source.i then look with an editor or pager inside source.i).

这篇关于C结构中的类型不完整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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