I am currently working on an embedded system and I have a component on a board which appears two times. I would like to have one .c and one .h file for the component.
<
You could make a portion of your structure private like this.
object.h
struct object_public {
uint32_t public_item1;
uint32_t public_item2;
};
object.c
struct object {
struct object_public public;
uint32_t private_item1;
uint32_t *private_ptr;
}
A pointer to an object
can be cast to a pointer to object_public
because object_public
is the first item in struct object
. So the code outside of object.c will reference the object through a pointer to object_public
. While the code within object.c references the object through a pointer to object
. Only the code within object.c will know about the private members.
The program should not define or allocate an instance object_public
because that instance won't have the private stuff appended to it.
The technique of including a struct as the first item in another struct is really a way for implementing single inheritance in C. I don't recall ever using it like this for encapsulation. But I thought I would throw the idea out there.