undefined C struct forward声明
我有一个头文件port.h,port.c和我的main.c
我收到以下错误:’ports’使用未定义的struct’port_t’
我以为我已经在我的.h文件中声明了结构,并且.c文件中的实际结构是可以的。
我需要有前向声明,因为我想在port.c文件中隐藏一些数据。
在我的port.h中,我有以下内容:
/* port.h */ struct port_t;
port.c:
/* port.c */ #include "port.h" struct port_t { unsigned int port_id; char name; };
main.c中:
/* main.c */ #include #include "port.h" int main(void) { struct port_t ports; return 0; }
非常感谢任何建议,
不幸的是,编译器在编译main.c时需要知道port_t
的大小(以字节为单位),因此需要在头文件中使用完整的类型定义。
如果要隐藏port_t
结构的内部数据,可以使用标准库如何处理FILE
对象的技术。 客户端代码仅处理FILE*
项,因此他们不需要(实际上通常不能)知道FILE
结构中实际的内容。 这种方法的缺点是客户端代码不能简单地将变量声明为该类型 – 它们只能指向它,因此需要使用某些API创建和销毁该对象,以及对象的所有使用必须通过一些API。
这样做的好处是你有一个很好的干净界面来说明必须如何使用port_t
对象,并允许你将私有事物保密(非私有事物需要getter / setter函数供客户端访问)。
就像在C库中处理FILE I / O一样。
我使用的常见解决方案:
/* port.h */ typedef struct port_t *port_p; /* port.c */ #include "port.h" struct port_t { unsigned int port_id; char name; };
您在function接口中使用port_p。 您还需要在port.h中创建特殊的malloc(和免费)包装器:
port_p portAlloc(/*perhaps some initialisation args */); portFree(port_p);
我会推荐一种不同的方式:
/* port.h */ #ifndef _PORT_H #define _PORT_H typedef struct /* Define the struct in the header */ { unsigned int port_id; char name; }port_t; void store_port_t(port_t);/*Prototype*/ #endif /* port.c */ #include "port.h" static port_t my_hidden_port; /* Here you can hide whatever you want */ void store_port_t(port_t hide_this) { my_hidden_port = hide_this; } /* main.c */ #include #include "port.h" int main(void) { struct port_t ports; /* Hide the data with next function*/ store_port_t(ports); return 0; }
在头文件中定义变量通常没有用。