undefined C struct forward声明

ant*_*009 20 c struct declaration forward

我有一个头文件port.h,port.c和我的main.c

我收到以下错误:'ports'使用未定义的struct'port_t'

我想,因为我在.h文件中声明了结构,并且.c文件中的实际结构是可以的.

我需要有前向声明,因为我想在port.c文件中隐藏一些数据.

在我的port.h中,我有以下内容:

/* port.h */
struct port_t;
Run Code Online (Sandbox Code Playgroud)

port.c:

/* port.c */
#include "port.h"
struct port_t
{
    unsigned int port_id;
    char name;
};
Run Code Online (Sandbox Code Playgroud)

main.c中:

/* main.c */
#include <stdio.h>
#include "port.h"

int main(void)
{
struct port_t ports;

return 0;
}
Run Code Online (Sandbox Code Playgroud)

非常感谢任何建议,

Mat*_*hew 25

不幸的是,编译器需要port_t在编译main.c时知道(以字节为单位)的大小,因此您需要在头文件中使用完整的类型定义.

  • @litb:你是什么意思?我相信在c ++中,main.cpp仍然需要port_t的完整定义才能创建"ports"实例. (5认同)
  • 当然史蒂夫是对的.即使是类,C++也是一样的.您需要在标头中使用完整的类定义,以便编译器知道它应该在堆栈上为该类型的变量保留多少空间.只有成员函数的实现不需要在头文件中. (3认同)

Mic*_*urr 16

如果要隐藏port_t结构的内部数据,可以使用标准库处理FILE对象的方法.客户端代码只处理FILE*项目,因此他们不需要(实际上通常不能)知道FILE结构中实际的内容.这种方法的缺点是客户端代码不能简单地将变量声明为该类型 - 它们只能有指向它的指针,因此需要使用某些API创建和销毁对象,以及对象的所有使用必须通过一些API.

这样做的好处是你有一个很好的干净界面来说明port_t必须如何使用对象,并允许你将私有事物保密(非私有事物需要getter/setter函数供客户端访问).

就像在C库中处理FILE I/O一样.


Han*_*Eck 6

我使用的常见解决方案:

/* port.h */
typedef struct port_t *port_p;

/* port.c */
#include "port.h"
struct port_t
{
    unsigned int port_id;
    char name;
};
Run Code Online (Sandbox Code Playgroud)

您在功能接口中使用port_p.您还需要在port.h中创建特殊的malloc(和免费)包装器:

port_p portAlloc(/*perhaps some initialisation args */);
portFree(port_p);
Run Code Online (Sandbox Code Playgroud)