The #ifndef FILE_H #define FILE_H ... #endif is called an include guard. It prevents the contents of the .h file from being included by the compiler more than once. For example, let's say you have a SomeClass.h file:
Code:
class SomeClass { };
And you have AnotherClass.h, which depends on SomeClass:
Code:
#include "SomeClass.h"
class AnotherClass: public SomeClass { };
And finally, you have MainProgram.cpp, which includes both AnotherClass.h and SomeClass.h:
Code:
#include "AnotherClass.h"
#include "SomeClass.h"
int main()
{
SomeClass someObject;
AnotherClass anObject;
}
In this scenario, SomeClass.h will be included twice: once directly by MainProgram.cpp, and once by AnotherClass.h. This will cause a naming conflict, as SomeClass will be defined twice. So using include guards prevents this problem: The first time the compiler sees the #ifndef FILE_H, it looks for a preprocessor symbol named "FILE_H." It doesn't find that, so it goes to the next line: "#define FILE_H". This causes the preprocessor to add "FILE_H" to it's list of defined symbols. So the next time it encounters "#ifndef FILE_H", it finds that FILE_H is defined, and it skips to the #endif.
This is the standard way of preventing multiple inclusions of .h files, but I prefer to simply put "#pragma once" at the top of every .h file, which accomplishes the same thing much more simply.
As for namespaces, no, a "using namespace xxx" is not equivalent to doing a bunch of "#include xxx_1". In c++ you can declare things within a namespace, like so:
Code:
namespace sards
{
class MyClass;
}
Now if you want to access MyClass from outside of the sards namespace, you have to use "sards::MyClass". If you don't want to type out the "sards::" part every time you use MyClass, you can say "using namespace sards;", which will allow you to use all the names in the sards namespace without the sards:: prefix.
Namespaces are used to prevent naming conflicts. If all code were in a single global namespace, there would be name conflicts in projects which use multiple libraries. All the c++ standard library is defined within the "std" namespace. So to use the standard library, you have three options: always use the "std::" prefix, use "using namespace std", or use e.g. "using std::string", which only imports "std::string" into the global namespace, and not all the stuff in namespace std.