1

Let's take an example of my project:

I have 2 files, file1.c and file2.c. Both of these files have a header file (file1.h and file2.h). I also have a struct.h file which contains:

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

Both of the header files (file1.h and file2.h) include struct.h and the main.c includes both file1.h and file2.h. Let's say this is the 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);
}

Now, in main.c I get the error: In included file: typedef redefinition with different types. I assume the error is because both file1.h and file2.h declare their own common structs from struct.h.

Any ideas on a solution for the problem?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
GoodBoyNeon
  • 103
  • 7
  • Use include guards. That's the standard approach to preventing multiple include issues. Looking to see if I can find a duplicate. If not, your test book should certainly discuss them. – Avi Berger Jan 22 '23 at 06:35
  • [This post might help](https://stackoverflow.com/q/1653958/631266) – Avi Berger Jan 22 '23 at 06:40

2 Answers2

1

This is a very common issue when include other file unites, and the solution is to always use include guards in your header file, e.g.

// 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

With this include guard, in your main.c, even it includes both file1.h and file2.h, there is only definition of the struct.

fluter
  • 13,238
  • 8
  • 62
  • 100
1

The standard way to deal with this issue is to enclose the definitions in struct.h inside a #if or #ifdef preprocessor directive to avoid duplicate definitions if the file is included more than once. This is commonly referred to as include guards.

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 */

You should use this method on all include files to prevent redundant definitions which cause compilation errors in many cases.

chqrlie
  • 131,814
  • 10
  • 121
  • 189