St.Antario
St.Antario

Reputation: 27385

Typedef of a type defined in a separate header file

I have two header files:

src/util/buffer.h:

//Namespace Src Util Buffer sub

struct sub_buffer{
    size_t size;
    void *buf;
};

//tons of static inline functions

src/lib_context.h:

   //Namespace Src Lib Context slc

   typedef struct sub_buffer slc_buffer; // Is this typedef ok?

   struct slc_context{
      //definition
   };

   void slc_set_buffer(slc_buffer *buf_ptr);

   //tons of other structs and functions

The thing that I was not sure about was the typedef struct sub_buffer slc_buffer;. There was a choice to include the src/util/buffer.h, but that would intoroduce tightly coupling to the header and it would be more difficult to replace it with e.g. another buffer definition containing flexible array member.

Is it common to introduce such a typedef to the structure that is defined in another header file so its implementation will be provided in the c file when including the header (but not to include one header to another header file)?

Upvotes: 0

Views: 1014

Answers (1)

unwind
unwind

Reputation: 399871

No, that would be an error.

You probably meant

typedef struct sub_buffer slc_buffer;

in which case it's fine, you can always introduce typedef aliases to types, even without having those types defined in the scope you're in.

This is the reason the classical self-referencing "node" works:

typedef struct node node;
struct node {
  node *next;
  void *data;
};

Notice how on the first line a typedef for an unknown type is used.

Upvotes: 2

Related Questions