【发布时间】:2010-11-17 04:45:38
【问题描述】:
gcc 4.4.4 c89
在使用结构体隐藏实现文件中的元素时,我一直都是这样做的。
port.h 头文件
struct port_tag;
struct port_tag* open_ports(size_t port_id);
void close_ports(struct port_tag *port);
port.c 实现文件
#include "port.h"
typedef struct port_tag {
size_t port_id;
} port_t;
port_t* open_ports(size_t port_id)
{
port_t *port = malloc(sizeof *port);
if(port == NULL) {
return NULL;
}
port->port_id = port_id;
return port;
}
void close_ports(port_t *port)
{
if(port != NULL) {
free(port);
}
}
driver.c 驱动文件
#include "port.h"
int main(void)
{
size_t i = 0;
struct port_tag *port = NULL;
for(i = 0; i < 5; i++) {
port = open_ports(i);
if(port == NULL) {
fprintf(stderr, "Port [ %d ] failed to open\n", i);
}
close_ports(port);
}
return 0;
}
在上面的代码中,很明显标签名称是port_tag,而实际的typedef名称是port_t。
但是,我正在重新设计一些代码。我发现他们使用了一种我以前从未见过的不同方法。我对他们的方法有一些疑问。
channel.h 头文件
typedef struct channel_t channel_t;
channel_t* open_channels(size_t channel_id);
void close_channels(channel_t *channel);
channel.c 实现文件
#include "channel.h"
struct channel_t {
size_t channel_id;
};
channel_t* open_channels(size_t channel_id)
{
channel_t *channel = malloc(sizeof *channel);
if(channel == NULL) {
return NULL;
}
channel->channel_id = channel_id;
return channel;
}
void close_channels(channel_t *channel)
{
if(channel != NULL) {
free(channel);
}
}
driver.c 驱动文件
#include "channel.h"
int main(void)
{
size_t i = 0;
channel_t *channel = NULL;
for(i = 0; i < 5; i++) {
channel = open_channels(i);
if(channel == NULL) {
fprintf(stderr, "Channel [ %zu ] failed to open\n", i);
}
close_channels(channel);
}
return 0;
}
1) 当他们声明了 typedef'ed 结构时,它是标签名称或 结构本身?
typedef struct channel_t channel_t;
2) 在实现文件中,结构体的名称不应该跟在最后一个花括号后面吗?
struct channel_t <-- tag name {
size_t channel_id;
} <-- itsn't this the name of the typedef'ed struct;
非常感谢您的建议,
【问题讨论】:
-
+1 对于一个有趣且精心提出的问题。我学到了一些东西,因为我总是将结构的实现暴露给客户端代码,事实证明这是不必要的。