如何在包含文件中部分声明typedef的结构

Art*_*wri 5 c typedef include

我试图最小化#include文件的相互依赖性作为一般做法.

在xxx.h我有:

struct my_struct;  // partial decl to satisfy use of my_struct*
void funct(struct my_struct* ms);  // uses the partial def
Run Code Online (Sandbox Code Playgroud)

如何使用typedef'd结构进行类似的部分decl?我在第三个#include中有一个实际的decl看起来像(例如在yyy.h中):

typedef struct my_data_s {
  int ival;
  ... struct's other components ...
} my_data_t;
Run Code Online (Sandbox Code Playgroud)

我只想在xxx.h中引用一个代表decl来引用typedef:

typedef struct my_data_s  my_data_t;  // actual full decl is elsewhere
void funct2(my_data_t* md);   
Run Code Online (Sandbox Code Playgroud)

此尝试导致"重新定义typedef my_data_t"错误.(使用gcc 4.4.3/Ubuntu 10.4)其他随机搜索尝试(例如,向typedef添加'{}')也会出错.

我知道编译器只需要知道函数需要一个指针,所以看起来这应该是可能的.到目前为止,没有发现任何编译错误/警告.

我看了其他问题和答案,找不到解决这个问题.似乎应该有一个众所周知的方法来做到这一点(?!)(我知道我可以#include yyy.y每当我#include xxx.h - 试图避免这种依赖.)谢谢.

Art*_*wri 0

这就是我们小组决定做的事情。它代表了几个相互冲突的要求/愿望的妥协。我发帖是为了展示另一种方法,因此该帖子的读者有多种选择。它代表了我们情况的最佳答案。

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;
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

obj_a.c

...
#include "obj_a.h"
...
// implementations of functions declared in obj_a.h
Run Code Online (Sandbox Code Playgroud)

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, ...);
...
Run Code Online (Sandbox Code Playgroud)

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's no need for 
// this include.
#include "obj_a.h"  // only if obj_b uses 
...
// obj_b's function implementations
Run Code Online (Sandbox Code Playgroud)

理由/条件

  • typedef 和 struct 放在一起
  • 使用 obj_X 的 .c 文件必须 #include "obj_X.h" 以显示该使用
  • 一般来说,避免使用 .h 文件,包括其他 .h 文件;只有“defs.h”文件被 #include 到 .h 文件中。
  • 避免仅仅为了处理依赖关系而 #include'ing 文件;IOW 避免 #include'ing obj_a.h 只是因为它在 obj_b.h 中使用