问题
I have the below project structure:
file - a.h
#pragma once
struct best_fit_struct {
void *next;
size_t size;
};
file - 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;
file - b.c
#include "a.h"
#include "b.h"
on compiling b.c using gcc -c b.c
, it throws the following error
file best_fit_mm has incomplete data type
I have included a.h
before b.h
, so the ordering looks proper to me.
Surprisingly, if I include a.h
inside b.h
, things gets resolved.
回答1:
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.
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
).
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.
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)
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
).
回答2:
If file b.h
uses items form file a.h
then you must, by definition, include a.h
within b.h
来源:https://stackoverflow.com/questions/41306372/incomplete-type-in-c-struct