Including implementation in header file

I am not entirely understanding the format of a header file. Why we need to include the implementation file at the end of a header file, and what does the characters after #ifndef and #define do? For instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//What does the character "object" do after #ifndef? Can we do without it?
#ifndef Object
#define Object

#include "ObjectInterface.h"

template<class ItemType>
class Object 
{
public:
   Object();


private:
   ItemType item;
};

//Why do we include "LinkedList.cpp" at the end of the header file?
#include "LinkedList.cpp"
#endif  


Also, I read somewhere that if you compile the same program twice, there will be declarations of the same variables twice and so we need to make sure every file is compiled only once, is this correct?
Last edited on
Why we need to include the implementation file at the end of a header file,

Never seen that anywhere.
what does the characters after #ifndef and #define do?

Preprocessor directives: http://www.cplusplus.com/doc/tutorial/preprocessor/
Don't need to include the implementation file at the bottom unless you are using templates. If you are using templates, then use "#include "LinkedList.hpp" at the bottom of the header, before #endif.

You are using templates, so your implementation file should be "LinkedList.hpp", and you need to change #include "LinkedList.cpp" to #include "LinkedList.hpp" .
Make sure your implementation file ends in ".hpp", or you could just write all of the implementation in the header file.

Also, I read somewhere that if you compile the same program twice, there will be declarations of the same variables twice and so we need to make sure every file is compiled only once, is this correct?

Not quite. If you are compiling the same thing again, the old compilation is thrown out and the data is compiled again. If you only change your .cpp or .hpp file, only that will be compiled again. You don't need to worry about compiling more than once. It's more complex than that, but, in short, no, we don't need to worry about that. The compiler will take care of all of that for you.
Topic archived. No new replies allowed.