I have seen articles in English that talk about this, as far as I can understand they are used for encapsulation in C. Can someone explain what exactly is an incomplete type and an opaque pointer? And what uses do they have in C?
I have seen articles in English that talk about this, as far as I can understand they are used for encapsulation in C. Can someone explain what exactly is an incomplete type and an opaque pointer? And what uses do they have in C?
An incomplete type is as its name implies, a type without a definition, which is complemented with opaque pointers, consider the following example:
fecha.h
fecha.c
You have an opaque implementation by providing only the data structure declaration
date_t
, allowing the user of your library only a pointer to the structure and a set of functions to give it behavior.Everything is defined in the code file that will be compiled to deliver the binary to whoever uses it.
These implementations are used to keep the code as hidden as possible from end users, so they don't know the content of the pointer internally.
In the end:
A practical example:
Note that it has been upside down so it may not work at all (Pending until I find my computer) .
Try the following command line to get results:
It should return the following result:
SN 1 :
-std=c11
because you never have to lose style.Finally, the main advantages of implementing this type of opacity in C is that you limit the number of changes that users are able to make to your structure, which has a side effect, since not everyone wants to do things your way . , but the implementation is useful when making software to sell.
And like everything in C, it is not good to abuse this type of methodology.
1 : Side note.