Declare a structure and function reference that use each other

I need to declare a structure (typedef'd) and a reference to a function (typedef'd) with a sick C. This is my code:

typedef void (*monitor_calback)(monitor_data*, short int, short int, void*);

typedef struct
{
    int port;
    unsigned char port_state;

    monitor_calback cb_high[8];
    void *cb_high_data[8];
    monitor_calback cb_low[8];
    void *cb_low_data[8];
} monitor_data;

But, of course, it does not compile, because we do not know about the structure when declaring a function.

I got this, but it looks a bit dirty and a little hard to read.

struct _monitor_data;

typedef void (*monitor_calback)(struct _monitor_data*, short int, short int, void*);

typedef struct _monitor_data
{
    int port;
    unsigned char port_state;

    monitor_calback cb_high[8];
    void *cb_high_data[8];
    monitor_calback cb_low[8];
    void *cb_low_data[8];
} monitor_data;

Are there any better ways to do this?

+3
source share
3 answers

You can print the structure before defining it:

typedef struct _monitor_data monitor_data;

typedef void (*monitor_calback)(monitor_data*, short int, short int, void*);

struct _monitor_data
{
    int port;
    unsigned char port_state;

    monitor_calback cb_high[8];
    void *cb_high_data[8];
    monitor_calback cb_low[8];
    void *cb_low_data[8];
};

, monitor_data , struct _monitor_data . monitor_callback, monitor_data * -, monitor_callback , , monitor_data .

C, , .

+2

, tho:

    #define monitor_data struct _monitor_data
    typedef void (*monitor_calback)(monitor_data*, short int, short int, void*);

    typedef struct _monitor_data
    {
        int port;
        unsigned char port_state;

        monitor_calback cb_high[8];
        void *cb_high_data[8];
        monitor_calback cb_low[8];
        void *cb_low_data[8];
    };
0

There is no better way because of the behavior typedef.

0
source

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


All Articles