C -不同类型的Typedef重定义



以我的项目为例:

我有两个文件,file1.cfile2.c. 这两个文件都有一个头文件(file1.h)和file2.h(. 我也有一个结构。h包含:

的文件
typedef struct {
char region[80];
int startDate;
int endDate;
int startTime;
int endTime;
} Schedule;

两个头文件(file1.h)和file2.hstruct.h和main.c包含file1.hfile2.h. 假设这是main。c:

#include <stdio.h>
#include "file1.h"
#include "file2.h"
int main() {
/* function from file1.h */
int num1 = sum(1, 3);
/* function from file2.h */
int num2 = mul(4, 5);
}
现在,在main.c中我得到错误:In included file: typedef redefinition with different types。我认为错误是因为file1.hfile2.hstruct.h声明它们自己的公共结构. 对于这个问题有什么解决办法吗?

处理此问题的标准方法是将struct.h中的定义包含在#if#ifdef预处理器指令中,以避免在文件包含多次时重复定义。这通常被称为include守卫.

struct.h:

#ifndef STRUCT_H_INCLUDED
#define STRUCT_H_INCLUDED
typedef struct {
char region[80];
int startDate;
int endDate;
int startTime;
int endTime;
} Schedule;
#endif /* STRUCT_H_INCLUDED */

你应该在所有的include文件上使用这个方法,以防止在很多情况下导致编译错误的冗余定义。

在包含其他文件单元时,这是一个非常常见的问题,解决方案是始终在头文件中使用include保护,例如

// struct.h
#ifndef INCLUDED_STRUCT_H
#define INCLUDED_STRUCT_H
typedef struct {
char region[80];
int startDate;
int endDate;
int startTime;
int endTime;
} Schedule;
#endif

有了这个包含保护,在你的main.c中,即使它包括file1.hfile2.h,也只有struct的定义。

最新更新