问题如下
多个.c和.h文件
其中cloth.h
分布被hat.h
和paths.h
包含,编译时出现如下问题:
error: redefinition of struct _Cloth
我的cloth.h
定义如下:
#include <stdio.h>
#include <stdlib.h>
#include "retval.h"
struct _Cloth;
typedef struct _Cloth Cloth;
typedef Cloth* (*createClothFunc)();
typedef void (*deleteClothFunc)(Cloth* thiz);
struct _Cloth
{
createClothFunc createCloth;
deleteClothFunc deleteCloth;
};
_Cloth 结构体先声明,再定义,显然满足C语言的语法,那麽以上重复定义的异常来自那里呢?
问题解决
紧接着发现该问题是在编译时检测出来的,那麽分析一下编译器在编译C语言都做了一些什么呢?
-
预处理
-
编译
-
汇编
-
链接
详细讲解可以参考C语言编译过程
关于#ifndef
条件编译 的作用如下
#ifndef x //先测试x是否被宏定义过
#define x
code 1 //如果x没有被宏定义过,定义x,并编译code 1
#endif
code 2 //如果x已经定义过了则编译程序段2的语句,“忽视”程序段1。
显然其最主要的目的是为了防止头文件 的重复包含和编译。
到此,以上结构体重定义的问题就比较清晰了,cloth.h
被重复包含,且因为cloth.h
未指定条件编译,被重复编译了。此时编译器会认为cloth.h
中的结构体定义是被重复定义得。
在多文件的开发过程种,需要规范化头文件的定义,增加条件编译相关的代码,防止头文件被重复包含导致的编译 异常。