Search code examples
cstructincludeheader-files

C - Typedef redefinition with different types


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?


Solution

  • 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.