我有一个头文件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 <stdio.h>
#include "port.h"

int main(void)
{
struct port_t ports;

return 0;
}

非常感谢任何建议,

有帮助吗?

解决方案

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

其他提示

如果要隐藏 port_t 结构的内部数据,可以使用标准库如何处理 FILE 对象的技术。客户端代码只处理 FILE * 项,因此他们不需要(实际上通常不能)知道 FILE 结构中的实际内容。这种方法的缺点是客户端代码不能简单地将变量声明为该类型 - 它们只能指向它,因此需要使用某些API创建和销毁对象,并且 all 对象的使用必须通过一些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;
};

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

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 <stdio.h>
#include "port.h"
int main(void)
{
    struct port_t ports;
    /* Hide the data with next function*/
    store_port_t(ports);
    return 0;
}

在头文件中定义变量通常没有用。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top