there are facilities to guard the header file to be included several times like this:
1 2 3 4
#ifndef XXX_H_
#define XXX_H_
#endif
so I guess if I put my variable definition in this guard and member function definition in this guard(but outside the class body), this guard will guarantee my error free from compiler's "multi-definition". But it seems it doesn't work as I think. What are the usage of this guard at all? Thanks.
The guard prevents the same header from being included multiple times in one cpp file. This is meant to prevent compiler errors where you define the same class/function multiple times.
Your problem is a linker error in which the same function is defined in multiple cpp files.
Take the following example:
1 2 3 4 5
// a.cpp
void func()
{
cout << "from a.cpp";
}
1 2 3 4 5
// b.cpp
void func()
{
cout << "from b.cpp";
}
1 2 3 4 5 6 7 8
// main.cpp
void func();
int main()
{
func(); // which 'func' does this call? the one in a.cpp or the one in b.cpp?
}
The question above is why the linker will error. If the same function body exists in 2 cpp files, you effectively have two different functions with the same name. So it's impossible for the linker to know which one to use, and therefore it will spit an error at you.
Global variables have the same problem. If you have multiple variables with the same name in multiple cpp files, which variable is the linker suppose to use?
Oh, but you're perfectly right. It prevents something from being defined multiple times... except that it prevents XXX_H_ from being redefined, not anything inside XXX_H_.
Does you mean the guard prevent people to define different content in a same name header file? But aren't we required to put the header file in the local directory? There won't be any two header files using the same name, right? a little bit confused!
EDIT: If you have two header files named different things but they include the same definitions, that guards against any negative effects of including them both.
Really? You mean if I put something in northflyheaderfile.h and there are NORTHFLYHEADERFILE_H_ guard,
while put the same thing in Albatross.h with ALBATROSS_H_ guard, and when I do this