Reputation: 11
I am reading a book and it states the following principle for what to put in the header file:
"What you can put into header files? The basic rule is “only declarations,” that is, only information to the compiler but nothing that allocates storage by generating code or creating variables. This is because the header file will typically be included in several translation units in a project, and if storage for one identifier is allocated in more than one place, the linker will come up with a multiple definition error ..."
However, it then gives an example of such header file:
#ifndef STACK_H
#define STACK_H
struct Stack
{
struct Link
{
void* data;
Link* next;
void initialize(void* dat, Link* nxt);
} *head;
...
};
#endif
Isn't the variable "head" an object and violating this rule? Even it is a pointer, it will take storage and cause issues if multiple compilation units include this header file leading to "multiple definition"?
Upvotes: 1
Views: 86
Reputation: 5823
When deciding what needs to be put into header files, the question that should be running through your head is "Does this need to be defined beforehand?". Before viewing an implementation, one would need to know definitions of user defined objects (structs and classes) and method (function) definitions before they are called in the implementation.
What goes in header files?
In this case, nothing is allocated. All you have said here is that we are defining Stack to include a member which is a pointer to a Link. We, of course, also need to define link, which is defined to be used the scope of a Stack structure.
If I continue on, I will sound like this thread, which I will delegate your attention to. Understanding the idea of header files, can always be a tricky obstacle.
Upvotes: 0
Reputation: 52377
You are declaring a member variable. Even if it is not a pointer it is not a problem. It is a part of a class (struct) declaration.
Only when you instantiate an object of type Stack
, storage allocation actually will take place.
Upvotes: 2