How can I hide the declaration of a struct in C?

c

Solution

Have a look at this example of a library, using a public header file, a private header file and an implementation file.

In file public.h:

struct Point;

struct Point* getSomePoint();

In file private.h:

struct Point
{
    int x;
    int y;
}

In file private.c:

struct Point* getSomePoint()
{
    /* ... */
}

If you compile these three files into a library, you only give public.h and the library object file to the consumer of the library.

`getSomePoint` has to return a pointer to `Point`, because public.h does not define the size of `Point`, only that is a struct and that it exists. Consumers of the library can use pointers to `Point`, but can not access the members or copy it around, because they do not know the size of the structure.

Regarding your further question: You can not dereference because the program using the library does only have the information from private.h, that does not contain the member declarations. It therefore can not access the members of the point structure.

You can see this as the encapsulation feature of C, just like you would declare the data members of a C++ class as private.

Problem

In the question Why should we typedef a struct so often in C?, unwind answered that: In this latter case, you cannot return the Point by value, since its declaration is hidden from users of the header file. This is a technique used widely in GTK+, for instance. How is declaration hiding accomplished? Why can't I return the Point by value? ADD: I understood why I can't return the struct by value, but, is still hard to see why i can't deference this point in my function. i.e. If my struct have member named y, why i can't do it? ``` pointer_to_struct->y = some_value; ``` Why should I use methods to do it? (Like Gtk+) Thanks guys, and sorry for my bad english again.

Original source

Related problems