2

I am unable to compile the following code because my gcc compiler (MSYS2 12.1.0) is not recognizing the struct that I have created in my header file diffDates.h.

Below is the header file

#ifndef DIFFDates_H
#define DIFFDates_H

int getDifference(Date dt1, Date dt2);

// A date has day 'd', month 'm' and year 'y'
struct Date {
    int d, m, y;
};

#endif

Below is my main file makefiles.c

#include <stdio.h>
#include <string.h>
#include "diffDates.h"

int main()
{
    char str_start[10];
    char str_end[10];
    printf("Please enter the start date in dd.mm.yy: ");
    scanf("%s", str_start);
    printf("\nPlease enter the end date in dd.mm.yy:");
    scanf("%s", str_end);

    return 0;
}

Below is the output from the GCC compiler

gcc makefiles.c -o makefiles     
In file included from makefiles.c:7:
diffDates.h:4:19: error: unknown type name 'Date'
    4 | int getDifference(Date dt1, Date dt2);
      |                   ^~~~
diffDates.h:4:29: error: unknown type name 'Date'
    4 | int getDifference(Date dt1, Date dt2);
      |                             ^~~~
diffDates.h:19:20: error: unknown type name 'Date'
   19 | int countLeapYears(Date d)
      |                    ^~~~
diffDates.h:40:19: error: unknown type name 'Date'
   40 | int getDifference(Date dt1, Date dt2)
      |                   ^~~~
diffDates.h:40:29: error: unknown type name 'Date'
   40 | int getDifference(Date dt1, Date dt2)
      |    

I would like to know what is wrong because I can include functions in the main file but structs are not defined for some reason.

zahid kamil
  • 165
  • 6
  • 1
    You have to refer to each `Date` as `struct Date` every time. Or you can change your definition to `typedef struct Date { int d, m, y; } Date;` or `typedef struct { int d, m, y; } Date;`. See [this question](https://stackoverflow.com/questions/1675351/typedef-struct-vs-struct-definitions) for more info. Also, your function is declared before the type is defined. – Dmytro Oct 05 '22 at 01:29
  • Thanks. I was stupid to realize it was C++. – zahid kamil Oct 05 '22 at 01:42

1 Answers1

2

first of all, in C. to define a struct and declare an instance of that struct, you either type:

struct Date {
    int d, m, y;
};

int getDifference(struct Date dt1, struct Date dt2);

Or

typedef struct Date {
    int d, m, y;
}Date;

int getDifference(Date dt1, Date dt2);

second of all, the line :

int getDifference(Date dt1, Date dt2);

must come after :

typedef struct Date {
    int d, m, y;
}Date;

not before it, as during compilation. when the compiler reaches that line int getDifference(Date dt1, Date dt2); , it has no information about the user data type called Date .

so edit the header file to be :

#ifndef DIFFDates_H
#define DIFFDates_H

// A date has day 'd', month 'm' and year 'y'
typedef struct Date {
    int d, m, y;
}Date;

int getDifference(Date dt1, Date dt2);

#endif
abdo Salm
  • 1,678
  • 4
  • 12
  • 22