我知道 typedef'ing 允许您在不使用 struct 关键字的情况下引用结构。然而,有了这个:
typedef struct SYSTEM SYSTEM;
我在 C
API 中见过此 typedef,但之前struct SYSTEM
尚未定义。
事实上,仅包含该行的 .c
文件将自行编译。
编译器认为SYSTEM(或struct SYSTEM)
实际上是什么?
非常感谢!
最佳答案
不需要定义该结构。只需声明即可。您提供的 typedef 声明包含 struct SYSTEM
的声明。
所以它相当于:
struct SYSTEM;
typedef struct SYSTEM SYSTEM;
多亏了这个 typedef,SYSTEM
现在命名了一个不完整的类型,因此您可以像 SYSTEM *
在接口(interface)定义中使用它,而无需公开该类型的实际定义结构体,可以保持私有(private):
public_header.h:
typedef struct SYSTEM SYSTEM;
SYSTEM * create_system();
int do_useful_thing_with(SYSTEM * system, int count, void * addr);
void destroy_system(SYSTEM * system);
private_impl.c:
#include <public_header.h>
struct SYSTEM { int a; char b[12]; float q; void * next; };
SYSTEM * create_system()
{
SYSTEM * p = malloc(sizeof *p);
if (p) { p->a = 2; p->q = 1.5; }
return p;
}
void destroy_system(SYSTEM * system)
{
free(system);
}
// etc.
关于c - 这段C代码是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17515919/