How to partially declare a structure that is typedef'ed when in an included file

I am trying to minimize the interdependence of #include files as a general practice.

In xxx.h I have:

struct my_struct;  // partial decl to satisfy use of my_struct*
void funct(struct my_struct* ms);  // uses the partial def

How to make a similar partial declaration using a typedef'd structure? I have an actual declaration in some third #include that looks like (e.g. yyy.h):

typedef struct my_data_s {
  int ival;
  ... struct other components ...
} my_data_t;

I just need a decl representative in xxx.h that references typedef:

typedef struct my_data_s  my_data_t;  // actual full decl is elsewhere
void funct2(my_data_t* md);   

This attempt causes a "typedef error override my_data_t". (Using gcc 4.4.3 / Ubuntu 10.4) Other random search attempts (like add '{}' to typedef) also give errors.

, , , , . , /.

, . , (?!) ( , # yyy.y , #include xxx.h - .) .

+5
3

. /. , , . .

obj_a_defs.h

// contains the definition
// #include'd only by other .h files
...
#define ... // as needed for struct definition
...
typedef struct obj_a {
  ...
} obj_a;

obj_a.h

// contains the 'full info' about obj_a: data and behaviors
// #include'd by other .c files
...
#include "obj_a_defs.h"
...
// declares functions that implement 
// the behaviors associated with obj_a

obj_a.c

...
#include "obj_a.h"
...
// implementations of functions declared in obj_a.h

obj_b.h

// a 'user' of obj_a that uses obj_a as arg
#include "obj_a_defs.h"  // to get the typedef    
...
int some_b_funct(obj_a* obja, ...);
...

obj_b.c

// Defines the 'contract' that this implementation
// is meeting.
#include "obj_b.h"
...
// This .c file includes obj_a.h only if it
// uses the functions defined for obj_a.
// If obj_a is used only to 'pass through'
// to other modules, there no need for 
// this include.
#include "obj_a.h"  // only if obj_b uses 
...
// obj_b function implementations

/

  • typedef struct
  • .c , obj_X, #include "obj_X.h" ,
  • .h, .h ; 'defs.h' # include'd .h .
  • # include'ing ; IOW # include'ing obj_a.h , obj_b.h
0

:?

xxx.h

struct my_data_s;
typedef struct my_data_s my_data_t;

yyy.h

#include "decl.h"
struct my_data_s {
   int foo;
};
+3

C99 does not allow repeating typedef, C11 does.

Just do it typedefonly once and always first it:

typedef struct my_data  my_data;

There is also no need to choose different names for the tag structand identifier typedef.

+3
source

All Articles