C programming decoupling interface from implementation with struct forward declaration

前端 未结 2 1137
孤街浪徒
孤街浪徒 2020-12-20 18:33

I am writing a C program and using gcc 4.4.6 to compile. I do not want to use a c++ compiler.

I am implementing a component and I intend to have several instances of

2条回答
  •  我在风中等你
    2020-12-20 18:57

    Having structs hidden has advantages and disadvantages. A hidden struct can never be allocated by the client without constructor. A hidden struct requires a destructor and the client is required to remember calling it. This is an advantage or a disadvantage depending on your requirement.

    Here are two implementations for comparison:

    #include 
    #include 
    
    /*VIVIBLE.h*/
    typedef struct
    {
        int number;
    }VISIBLE;
    void VISIBLE_INIT(VISIBLE * me, int num);
    void VISIBLE_PRINT(const VISIBLE * me);
    
    /*VIVIBLE.c*/
    void VISIBLE_INIT(VISIBLE * me, int num) { if(me) me->number = num; }
    void VISIBLE_PRINT(const VISIBLE * me) { if(me) printf("%i\n", me->number); }
    
    /*SECRET.h*/
    struct CLIENT;
    void CLIENT_CTOR(struct CLIENT ** me, int num);
    void CLIENT_DTOR(struct CLIENT ** me);
    void CLIENT_PRINT(const struct CLIENT * me);
    
    /*SECRET.c*/
    typedef struct CLIENT
    {
        int number;
    }CLIENT;
    void CLIENT_CTOR(CLIENT ** me, int num)
    {
        if (me)
        {
            *me = (CLIENT*)malloc(sizeof(CLIENT));
            (*me)->number = num;
        }
    }
    void CLIENT_DTOR(CLIENT ** me)
    {
        if (me && *me) free(*me);
        *me = 0;
    }
    void CLIENT_PRINT(const CLIENT * me) { if(me) printf("%i\n", me->number); }
    
    /*main.c*/
    void visible()
    {
        VISIBLE vis; // client can allocate memory
        VISIBLE_INIT(&vis, 4);
        VISIBLE_PRINT(&vis);
        //if there is no need for a destructor the client does not need to call one
    }
    
    void hidden()
    {
        CLIENT * hidden; 
        CLIENT_CTOR(&hidden, 3);
        CLIENT_PRINT(hidden);
        CLIENT_DTOR(&hidden); //Client is never allowed to forget the destructor
    }
    
    int main()
    {
        visible();
        hidden();
    }
    

提交回复
热议问题