Sunday, 25 February 2018

c - How do structs behave in terms of visibility to other files?



This is taken from an answer to a different question on SO:




A structure definition is private to a source file unless placed in a
shared header file. No other source file can access the members of the
struct, even if given a pointer to the struct (since the layout is not

known in the other compilation unit).



If the struct needs to be used elsewhere, it must be used only as a
pointer. Put a forward declaration of the form struct structname;
typedef struct structname structname; in the headerfile, and use
structname * everywhere else in your codebase. Then, since the
structure members appear only in one source file, the structure's
contents are effectively 'private' to that file.





This confuses me. Why can you only use pointers to a struct even if you include a header file that declares it (but does not define it)?



I mean, if I include a header that declares a function, a function which is defined in a separate implementation file, I can still access that function-- why are structs different? Why are their members private even if you can get to the declaration?


Answer



It has nothing to do with visibilty. The quote is referring to a struct forward declaration (so, no definition available)



The header effectively contains something like :



struct X;  // No definition available



A forward declaration introduces an incomplete type. There are very few things you can do with an incomplete type, but one of them is declaring a pointer (not dereferencing it).



As long as the compiler doesn't know the size of the struct, or it's members (it certainly can't with a simple forward declaration), it won't allow any declaration of an X, nor any dereferencing of a pointer to an X.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...