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

后端 未结 4 1535
清歌不尽
清歌不尽 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:09

    I agree with Marcelo Cantos, but also suggest simply adding a pointer inside the "public" structure, which points to the "private" contents, i.e:

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

    This approach is kind of like the "pimpl" ideom. The simplest approach by far is to do what Marcelo Cantos suggested.

提交回复
热议问题