I have a piece of code like this in .c
file:
typedef struct stack {
int maxsize;
int top;
int* items;
} stack;
I have read that when using header files, it's better to use this:
.h
typedef struct stack stack;
and do in
.c
struct stack {
int maxsize;
int top;
int* items;
};
My question is that, why can't we use only functions declarations in header files, and the typedef thing, we all do it in the c file? Why the above separation of typedef and struct into different files?
CodePudding user response:
The purpose is private encapsulation, a commonly used best practice during program design. What you describe here is often called "opaque type" since it uses the concept of forward declaration to block the user of your struct to learn or use the contents of the struct. The struct as seen from the header file is an "incomplete type" and the caller can't declare an object of such a type nor access any members inside it.
For details check out How to do private encapsulation in C?
CodePudding user response:
The client (i.e. the code that uses stack
) does not need to (and should not) care about the details of what a stack
actually is.
If you would put the details into the *.h file, you would need to compile the files that use the struct whenever the definition of the struct changes.
If it's separated, you only need to recompile stack.c
and not your entire program.