繁体   English   中英

未定义 C 结构前向声明

[英]undefined C struct forward declaration

我有一个 header 文件 port.h、port.c 和我的 main.c

我收到以下错误:“ports”使用未定义的结构“port_t”

我想我已经在 my.h 文件中声明了结构并且在 .c 文件中具有实际结构是可以的。

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

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

/* port.h */
struct port_t;

端口.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的大小(以字节为单位),因此您需要 header 文件中的完整类型定义。

如果要隐藏port_t结构的内部数据,可以使用标准库如何处理FILE对象等技术。 客户端代码只处理FILE*项目,因此它们不需要(实际上,通常不能)了解FILE结构中的实际内容。 此方法的缺点是客户端代码不能简单地将变量声明为该类型 - 它们只能具有指向它的指针,因此需要使用一些 API 来创建和销毁 object,以及 ZA8CFDE6331BD59EB2AC96B9666 的所有用途必须通过一些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 <stdio.h>
#include "port.h"
int main(void)
{
    struct port_t ports;
    /* Hide the data with next function*/
    store_port_t(ports);
    return 0;
}

在 header 文件中定义变量通常不好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM