目录
一、说明
二、例子
一、说明
给定头文件 father.h, son.h, daughter.h, son.h 和 daughter.h 里有各自的结构体,而 father.h 里有结构体囊括了 daughter.h 和 son.h 的结构体,也就是说 father 与 son 和 daughter 有了从属关系,即father.h 文件可以 include daughter.h 和 son.h, 而 son.h 和 daughter.h 不可以 include father.h 。没有从属关系的结构体不可以相互 include。
二、例子
①当 father.h 囊括 daughter.h 和 son.h,结果显示没有异常
father.h
1 #ifndef __FATHER_H__ 2 #define __FATHER_H_3 4 #include "daughter.h"5 #include "son.h"6 7 typedef struct father_8 {9int age;10float height;11float weight;12 13son_t son;14daughter_t daughter;15 16 }father_t;17 18 #endif
son.h
1 #ifndef __SON_H__ 2 #define __SON_H_3 4 typedef struct son_5 {6int age;7float height;8float weight;9 }son_t;10 11 #endif
daughter.h
1 #ifndef __DATGHTER_H__ 2 #define __DATGHTER_H_3 4 typedef struct daughter_5 {6int age;7float height;8float weight;9 }daughter_t;10 11 #endif
exam.c
1 #include <stdio.h> 2 #include "father.h"3 #include <string.h>4 int main(int argc, char** argv)5 {6father_t father;7memset(&father, 0, sizeof(father_t));8return 0;9 }
编译运行,结果显示并没有异常
# gcc exam.c # ./a.out
② 当 daughter.h 囊括 father.h
1 #ifndef __DATGHTER_H__ 2 #define __DATGHTER_H_3 4 #include "father.h"5 6 typedef struct daughter_7 {8int age;9float height;10float weight;11father_t father_s;12 }daughter_t;13 14 #endif
编译运行,出错
# gcc exam.cson.h:4:16: error: redefinition of ‘struct son_’typedef struct son_daughter.h:12:2: note: previous declaration of ‘daughter_t’ was here}daughter_t;son.h:4:16: note: originally defined heretypedef struct son_...
③ daughter.h 和 son.h 相互引用
daughter.h
1 #ifndef __DATGHTER_H__ 2 #define __DATGHTER_H_3 4 #include "son.h"5 typedef struct daughter_6 {7int age;8float height;9float weight;10 }daughter_t;11 12 #endif
son.h
1 #ifndef __SON_H__ 2 #define __SON_H_3 #include "daughter.h"4 typedef struct son_5 {6int age;7float height;8float weight;9 }son_t;10 11 #endif
编译运行,出错
# gcc exam.cdaughter.h:5:16: error: redefinition of ‘struct daughter_’typedef struct daughter_son.h:9:2: note: previous declaration of ‘son_t’ was here}son_t;son.h:9:2: error: conflicting types for ‘son_t’}son_t;...
结论:同 说明