简体   繁体   English

在单独的头文件中定义的类型的Typedef

[英]Typedef of a type defined in a separate header file

I have two header files: 我有两个头文件:

src/util/buffer.h : 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 : 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; 我不确定的是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 eg another buffer definition containing flexible array member. 可以选择包含src/util/buffer.h ,但这将导致与报头的紧密耦合,而用另一个包含灵活数组成员的缓冲区定义来替换它会更加困难。

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)? 将这样的typedef引入另一个头文件中定义的结构是否很常见,以便在包括头文件(但不包括另一个头文件的一个头文件)时在c文件中提供其实现?

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. 在这种情况下,即使没有在您的作用域中定义这些类型,也总是可以向类型引入typedef别名。

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. 注意第一行如何使用未知类型的typedef

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM