I have a ".c .h" couple of files. In the header file (.h), I define 2 typedef struct, let's call them TS1 and TS2.
Now, the type of one member of TS1 is TS2. I'd like that only TS1 is visible. TS2 should be hidden. TS2 should be only visible to the ".c" file.
How can I achieve this?
I like to name private header files with the '-internal' suffix. For your example, I'd have
foobar.c
#include "foobar-internal.h"
#include "foobar.h"
/* functions using `struct TS1` and `struct TS2` */
.
foobar.h
#ifndef H_FOOBAR_INCLUDED
#define H_FOOBAR_INCLUDED
struct TS1;
#endif
.
foobar-internal.h
#ifndef H_FOOBAR_INTERNAL_INCLUDED
#define H_FOOBAR_INTERNAL_INCLUDED
struct TS2 { int whatever; };
struct TS1 { int whatever; struct TS2 internal; };
#endif
Any code using your functions, includes the simpler "foobar.h"
and can use pointers to struct TS1
. It cannot directly use objects of either struct TS1
or struct TS2
type. In fact, by including just "foobar.h"
, the code has no idea there exists a struct TS2
type anywhere and can redefine it to its own purposes.
usercode.c
#include "foobar.h"
struct TS1 *x;
x = newTS1();
work(x);
destroyTS1(x);