c typedef(ed)opaque指针

Man*_*ish 15 c struct typedef opaque-pointers

我已经定义了一个不透明的结构和相关的API,如下所示:

typedef struct foo foo;
foo *create_foo(...);
delete_foo(foo *f);
Run Code Online (Sandbox Code Playgroud)

我无法在我的c文件中定义结构.给出重新定义错误.

typedef struct foo {
   int implementation;
}foo;
Run Code Online (Sandbox Code Playgroud)

我可以在没有typedef的c文件中使用foo,但我想要typedef(即直接使用它作为foo*).有办法吗?

Fre*_*Foo 22

你已经有了typedef标题,所以请struct foo在实现中包含它并在没有标题的情况下定义typedef.

foo.h:

typedef struct foo foo;
foo *create_foo(...);
delete_foo(foo *f);
Run Code Online (Sandbox Code Playgroud)

foo.c:

#include <foo.h>

struct foo { int implementation; };
/* etc. */
Run Code Online (Sandbox Code Playgroud)