Is there any workaround for making a structure member somehow 'private' in C?

后端 未结 4 1541
清歌不尽
清歌不尽 2020-12-25 08:52

I am developing a simple library in C, for my own + some friends personal use.

I am currently having a C structure with some members that should be somehow hidden fr

4条回答
  •  情歌与酒
    2020-12-25 09:24

    The usual techique is this:

    /* foo.h */
    typedef struct Foo Foo;
    
    Foo *foo_create(...);
    
    void foo_bark(Foo* foo, double loudness);
    
    /* foo.c */
    struct Foo {
      int private_var;
    };
    

    You can partially hide data members by defining Foo in the header and FooPrivate in the .c file thus:

    struct FooPrivate {
      Foo public_stuff;
      int private_var;
    }
    

    But then your implementation has to cast back and forth between Foo and FooPrivate, which I find to be a royal PITA, and is a maintenance burden if you change your mind later and want to make something private. Unless you want suck every last CPU cycle out of the code, just use accessor functions.

提交回复
热议问题