Reputation: 537
I want use a typedef struct that isn't already defined, but it is later. Is there anything like a struct prototype?
file container.h
// i would place a sort of struct prototype here
typedef struct
{
TheType * the_type;
} Container;
file thetype.h
typedef struct {......} TheType;
file main.c
#include "container.h"
#include "thetype.h"
...
Upvotes: 4
Views: 3241
Reputation: 42083
Replace this line:
// i would place a sort of struct prototype here
with these lines:
struct TheType;
typedef struct TheType TheType;
Since you need the type TheType
to be defined before type Container
is defined, you have to use forward declaration of type TheType
- and to do so you also need forward declaration of struct TheType
.
Then you will not define typedef TheType
like this:
typedef struct {......} TheType;
but you will define struct TheType
:
struct TheType {......};
Upvotes: 6
Reputation: 108978
You cannot define an object of an, as yet, undefined struct
; but you can define a pointer to such a struct
struct one {
struct undefined *ok;
// struct undefined obj; /* error */
};
int foo(void) {
volatile struct one obj;
obj.ok = 0; /* NULL, but <stddef.h> not included, so 0 */
if (obj.ok) return 1;
return 0;
}
The above module is legal (and compiles with gcc without warnings).
Upvotes: 1
Reputation: 477040
You can declare a struct inside the typedef:
typedef struct TheType_Struct TheType; // declares "struct TheType_Struct"
// and makes typedef
typedef struct
{
TheType * p;
} UsefulType;
Note though that you may only have at most one typedef
in one translation unit in C89 and C99 (this differs from C11 and C++).
Later on you must define the actual struct TheType_Struct { /* ... */ }
.
Upvotes: 1
Reputation: 43278
In container.h:
struct _TheType;
typedef struct _TheType TheType;
Than in thetype.h:
struct _TheType { ..... };
Upvotes: 5