Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interpret structure without definition?

Today I started working on FUSE opensource code, there i found few lines like this:

struct fuse_session;
struct fuse_chan;

I don't know how to interpret it , as far as i knew 'struct' is followed by structure name and then the name of variable. Where as in this case there is only one named entity followed by struct ,so this fuse session is structure variable or structure name itself.It may be some really basic thing but i am not able to find it anywhere.

like image 979
noob_coder Avatar asked Dec 26 '11 06:12

noob_coder


2 Answers

This is usually used for one of the following:

  1. You want to let the user of some module to know that this struct exist, but don't want to expose it's content. For example:

    in api.h:

    struct bar;
    
    void GetStruct(struct bar *);
    void SetActive(struct bar *, char);
    

    in your internal file:

    struct bar {
        char is_active;
    };
    
    void GetStruct(struct bar * st) {
        st = malloc(sizeof(struct bar));
    }
    
    void SetActive(struct bar * st, char active) {
        if (st != NULL)
            st->is_active = active;
    }
    

    This way you encapsulate the implementation and may change the struct later if needed without any impact on the using module.

  2. You want to use a structure (pointer) before declaring it. For example:

    struct bar;
    typedef int (*FooFuncType)(struct bar *);
    struct bar {
        FooFuncType a_func;        
    };
    

One important note:

If you only have the struct declaration, as in your question, you cannot refer to the struct directly, nor you may use the sizeof operator, only declare a pointer to the structure.

like image 159
MByD Avatar answered Sep 19 '22 16:09

MByD


Those are incomplete types or opaque types, and they are useful when the library interface only works with pointers to those types. You don't need to fill in all the details of what is in the structures so no code outside the library can ever access the data in the structure (legitimately). The code inside the library has a private header that supplies the details of what is in the structures, so the library can indeed work with the contents, but that is a detail hidden from the consumers of the library.

Incomplete types provide much better type safety than another alternative that is sometimes used, namely void pointers. It is too easy to get confused when there are multiple different types all represented by 'void *'. With incomplete types, you can properly distinguish between the different types, but still not reveal the details of how they are implemented.

like image 36
Jonathan Leffler Avatar answered Sep 19 '22 16:09

Jonathan Leffler