3

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"
...
Aditya Naidu
  • 1,362
  • 9
  • 12
gobien
  • 447
  • 5
  • 9

4 Answers4

5

In container.h:

struct _TheType;
typedef struct _TheType TheType;

Than in thetype.h:

struct _TheType { ..... };
Joshua
  • 40,822
  • 8
  • 72
  • 132
  • This is the correct answer; for the OP's further illumination, what is being done here is called a "forward declaration". – tbert Feb 05 '12 at 21:48
  • 2
    identifiers that begin with an `_` followed by an uppercase letter are reserved identifiers – ouah Feb 05 '12 at 21:57
  • Sorry. I recalled the rule being somewhat different. – Joshua Feb 05 '12 at 22:19
5

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 {......};
LihO
  • 41,190
  • 11
  • 99
  • 167
1

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 { /* ... */ }.

Community
  • 1
  • 1
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

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

pmg
  • 106,608
  • 13
  • 126
  • 198