problems with typedef on C
I writing some ADT on C:
I have two file date.c and date.h
inside date.c I have:
typedef struct Date_t {
int date;
char* month;
int year;
} Date;
inside date.h I have:
typedef Date pDate;
compiler gives me errors:
..\checking.h:15: error: syntax erro开发者_Go百科r before "pDate"
can somebody please explain what is wrong with my typedef, thanks in advance
EDIT:
with files all is ok, problem is, when I change my struct to:
struct Date_t {
int date;
char* month;
int year;
};
and pointer to:
typedef struct Date_t* pDate;
program works perfectly, so I want to understand the difference
You are probably declaring pDate as a typedef of Date before you even declared Date (since you are make pDate in the header).
You could do:
typedef struct Date_t {
int date;
char* month;
int year;
} Date;
typedef Date pDate;
All in you .c file.
As for your edit:
You are declaring the struct in the typedef:
typedef struct Date_t* pDate;
It is working because you are declaring struct
before you place pDate.
typedef /*see this struct here*/ struct /*huh?*/ Date_t* pDate;
The other has no struct
in it.
Assuming that you include the date.h
file before the struct definition of Date
. The problem is you're attempting to typedef
a type before it exists. The C compiler processes a file from top to bottom. So essentially what' you're saying is
typedef Date pDate;
typedef struct Date_t {
int date;
char* month;
int year;
} Date;
At the point of the first typedef
C has no idea what Date
is and hence the error. You need to switch the definitions.
typedef struct Date_t {
int date;
char* month;
int year;
} Date;
typedef Date pDate;
If you're including date.h before the structure definition in date.c, the compiler is complaining because it has no idea what 'Date' is referring to at the moment you say 'typedef Date pDate'.
You can use pointers to incomplete types without problems in C
(the problems come later)
struct Date; /* declaration of incomplete type */
typedef struct Date Date;
typedef Date *pDate;
pDate p;
p = NULL; /* ok, even when Date hasn't been defined */
p = malloc(sizeof *p); /* wrong! you cannot know the sizes of incomplete types */
Probably part of your confusion is due to a weirdness in C (not C++). With this declaration:
struct Date_t {...};
You create a structure type, that to use you must qualify with struct:
struct Date_t date1; /* Valid. */
Date_t date2; /* Not valid */
However, it is a common idiom in C to fix this with a typedef:
typedef struct {...} Date_t;
struct Date_t date1; /* invalid */
Date_t date2; /* Valid */
It is also a common idiom in C to do both together like this:
typedef struct _Date_t {...} Date_t;
struct _Date_t date1; /* Valid */
Date_t date2; /* Also valid */
And just to add to the confusion it is common to add a pointer typedef too:
typedef struct _Date_t {...} Date_t, * DateP;
Really, it is a historical artifact that in fixed in C++.
精彩评论