Overview of two different typedef'ing structure methods

gcc 4.4.4 c89

I always did the following when using structures to hide elements in the implementation file.

Port.h header file

struct port_tag;
struct port_tag* open_ports(size_t port_id);
void close_ports(struct port_tag *port);

Port.c implementation file

#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 file

#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;
}

In the above code, it is clear that the tag name is port_tag and the actual typedef name is port_t.

However, I am reconstructing one single code. And I found that they used a different method that I had never seen before. I have a few questions about their method.

channel.h header file

typedef struct channel_t channel_t;
channel_t* open_channels(size_t channel_id);
void close_channels(channel_t *channel);

Channel implementation file .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 file

#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) When did they declare a typedef'ed structure, which is the name of the tag or the name of the structure itself?

typedef struct channel_t channel_t;

2) Does the implementation file not follow the name of the structure following the last curly brace?

struct channel_t <-- tag name {
    size_t channel_id;
} <-- itsn't this the name of the typedef'ed struct;

Thanks so much for any advice,

+3
2

1. struct channel_t, typedef - channel_t.

, :

channel_t some_instance;

2. typedef , . , :

struct channel_t {
    size_t channel_id;
};

is channel_t. a struct typedef. , :

struct channel_t some_instance;

, .

+4
typedef struct channel_t channel_t;

, , "struct channel_t", , "channel_t". , "struct channel_t" "channel_t".

(2), . typedef - typedef, . ( , ) , , API ( "void *" ), .

+2

Source: https://habr.com/ru/post/1775350/


All Articles